Extra new lines when writing variables to file issue

by Grzegorz Kulikowski

Example:

PS C:\> gc c:\test.out
abc def
 gha
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.

$var1=”abc”

$var2=”def`n”

$var3=”gha”

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 :

http://technet.microsoft.com/en-us/library/dd347588.aspx

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

help about_operators | more


You may also like

2 comments

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.

Reply
psvmware October 25, 2012 - 8:00 pm

Glad it helped 😉

Reply

Leave a Reply

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