Why is PowerShell losing my carriage returns and line feeds?

I recommend

I was assigning the output of Git to a variable in a Windows PowerShell script and it looked as if I was losing the carriage returns and line feeds in the output. What is actually happening is the output of the executable is being broken out into an array of strings.

The following shows an example PowerShell session with an explanation following.

Windows PowerShell Losing Line Feed Example

  1. Running the git program returns output that is delimited by line breaks.
  2. Assign the output of the program to a variable.
  3. Write-Host the variable and the line breaks are gone >:-{
  4. You can see the variable is actually an array!
  5. You can create a string using the .NET String.Join function.
  6. Now Write-Host of the variable has the line breaks.

I created a short screen cast to explain this as well.

I hope this helps. Code on!

Technical PowerShell July 21, 2010


Comments