Error with substring ()

$fileName = "Name of TheFolder_NE_ED"
$lengthFileName = $fileName.length
$shortenLengthFileName = $lengthFileName - 5
Write-Host("Name of TheFolder_NE_ED").Substring($shortenLengthFileName,$lengthFileName)
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

      

I have a problem with a function SubString()

, these are errors with:

error message

I tried to print the values โ€‹โ€‹of my variables, but they looked ok.

+3


source to share


1 answer


In PowerShell, substring works a little differently.

With your existing code, you can try this:

$fileName = "Name of TheFolder_NE_ED"
$lengthFileName = $fileName.length
$shortenLengthFileName = $lengthFileName - 5
Write-Host("Name of TheFolder_NE_ED").Substring($shortenLengthFileName)

      

Explanation:

The first parameter within the substring must be the starting character index (in this case 18). Now from that letter it will start counting down to the character (which you must pass as the second parameter). Otherwise, it will default to the end of the line.



So, if you want to pass 2 parameters and do it, change it to:

Write-Host("Name of TheFolder_NE_ED").Substring($shortenLengthFileName,5)

      

For further reference follow Using a substring

Hope it helps.

+2


source







All Articles