Extra new lines when writing variables to file issue

by Grzegorz Kulikowski


PS C:\> gc c:\test.out
abc def
PS C:\>

The reason why ‘gha’ is in second line is that $var2 had a special sign of new line in it.

What i wanted to see in this file is to see 1 line ” abc def gha”. That’s just an example. I was printing to file some vms report and noticed that instead 1 line i had several variables that were making new line. In order to be sure that there is no additional characters besides text we can trim our variables.




PS C:\> echo “$var1 $($var2.trim()) $var3” > c:\test.out
PS C:\> gc C:\test.out
abc def gha

So whenever you will see in output files unexpected new lines,  just trim the variable. For people who are starting with powershell : $() means sub-expression, you can read about it here :


or you can read about it from your powershell console typing:

help about_operators | more

You may also like


Anonymous October 25, 2012 - 7:51 pm

I’ve been looking for a fix like this for about 2 days straight. Excellent find, thank you very much.

psvmware October 25, 2012 - 8:00 pm

Glad it helped 😉


Leave a Reply

Chinese (Simplified)EnglishFrenchGermanHindiPolishSpanish
Streaming live on Twitch right now.