Add-Content or substring is adding carriage return to variable

I'm outputting some lines of text that I'm pulling from a file and carriage returns are being added when I output this section after $strAcct:

Add-Content "C:\TestFile-Output.txt" ($strAcct+$strPart2)

So essentially what's printing in the file is $strAcct carriage return/new-line $strPart2

Here is all my code:

#Setting Variables
$data = get-content "C:\TestFile.txt"
$strAcct= @()
$strPart1= @()
$strPart2= @()
$strLength= @()


#For each line of text in variable $data, do the following
foreach($line in $data)
{
  #reseting variables for each time the FOR loop repeats
  $strAcct= @()
  $strPart1= @()
  $strPart2= @()
  $strLength= @()


   #We're saying that if the line of text is over 180 characters, were going to split it up into two different lines so MEDITECH can accept this note files
   if ( $line.length -gt 180)
   { $strLength = $line.length
     $strAcct += $line.substring(0,22) 
     $strPart1 += $line.substring(0,180)
     $strPart2 += $line.substring(181)

     #Create first and second line in text file for the string of text that was over 180 characters
     Add-Content "C:\TestFile-Output.txt" $strPart1
     Add-Content "C:\TestFile-Output.txt" ($strAcct+$strPart2)



   } 
   #If our line of text wasn't over 180 characters, just print it as is
   Else {
   Add-Content "C:\TestFile-Output.txt" $line

   }

}

Answers


$strAcct $strPart1 $strPart2 are all arrays in your code, which I don't think is your intention. Sending arrays of strings into a file will by default put each item on a new line (i.e. separated by CR-NL).

If you are trying to split long lines into 2 lines, based on the heuristic in your code, then below should work:

$data = get-content "C:\TestFile.txt"    

#For each line of text in variable $data, do the following
foreach($line in $data)
{   
   $newContent = 
     if ($line.length -gt 180)
     {
       $part1 = $line.substring(0,180)         
       $part2 = $line.substring(181)
       $acct = $line.substring(0,22)

       $part1
       $acct + $part2
     } 
     else
     {
       $line
     }

   Add-Content "C:\TestFile-Output.txt" $newContent
}

Need Your Help

Can thor accept unix-like options (such as -lv)?

ruby options thor

I've recently started using thor. I've set my script up with some global options, such as -l --logging and -v --verbose. I'd like users to be able to call my thor task with "-lv" rather than "-l -v...

c# if else statement

c# asp.net if-statement

I have a problem here because my coding is not working(error) and I don't know how to correct it.Can you guys check if this statement right or wrong? My conditions is