0

I'm getting errors with the code below. I'm trying to take lines in a text file that are over 180 characters and parse them to a new line. I have to take the first 22 characters and put it in from of part two since it contains inital data that's needed on the line:

$data = get-content "C:\TestFile.txt"
$strAcct= @()
$strPart1= @()
$strPart2= @()
$strLength= @()
foreach($line in $data)
{
   if ( $line.length -gt 181)
   { $strLength = $line.length
     $strAcct += $line.substring(0,22) 
     $strPart1 += $line.substring(0,180)
     $strPart2 += $line.substring(181,$strLength)

     Add-Content "C:\TestFile-Output.txt" $strPart1
     Add-Content "C:\TestFile-Output.txt" $strAcct $strPart2



   } 
   Else {
   Add-Content "C:\TestFile-Output.txt" $line

   }

}

1 Answer 1

1

Substring takes an index, and the number of characters to take starting from that index. Your third substring bombs, because you are trying to take more characters than there are in the string. Change it to $strLength - 181, or alternatively, you can leave the second parameter out entirely, to just take the rest of the string starting from the index in the first parameter.

Change this:

$line.substring(181, $strLength) 

to this:

$line.substring(181)

or even this:

$line.substring(181, $strLength - 181)
Sign up to request clarification or add additional context in comments.

6 Comments

I think that worked, thank you. I'm getting a bomb on this: Add-Content "C:\TestFile-Output.txt" $strAcct $strPart2 How do I print $strAcct AND $strPart2
Add-Content "C:\\TestFile-Output.txt" ($strAcct + $strPart2)
it's putting strPart2 on a new line instead of the same line with $strAcct. Any ideas?
It sounds like you have a newline somewhere around the end of $strAcct or the beginning of $strPart2... anyway, your problem is solved. That sounds like a different issue.
hmmmm, it's just grabbing from the string of text through this command and should only be grabbing the characters till the end of the string: $strPart2 += $line.substring(181) no new lines
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.