Extra new lines when writing variables to file issue


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


Advertisements

2 thoughts on “Extra new lines when writing variables to file issue

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s