Home > front end >  Powershell error during removal of first character from each line of a file
Powershell error during removal of first character from each line of a file

Time:05-25

Thanks in advance for your help. I found a way to remove the first character of each line in a file:

enter image description here

Powershell -command "get-content %INFILE% | foreach {$_.substring(1)}" > %OUTFILE%

I'm able to get the output file, however, i keep getting a bunch of these errors:

enter image description here

CodePudding user response:

This happens when you have blank lines in the input file (possibly even a trailing LF). In this case line length will be zero (as Get-Content strips CRLF from each line), so start index 1 for String.Substring() will be invalid, exactly as the error message says.

Possible fix:

Powershell -command "get-content %INFILE% | foreach {$_.Substring([Math]::Min(1, $_.Length))}" > %OUTFILE%

I'm using function Math.Min() to ensure the start index won't be greater than the line length.

  • Related