Adding New Lines to Strings

by Dec 15, 2011

In a previous tip you learned that text arrays can easily be multiplied. The same is true for assignment operators such as +=. When you apply this operator to a string, it appends a text:

PS> $text = "Hello"
PS> $text += "World"
PS> $text
HelloWorld

When you apply it to a string array, it adds new lines:

PS> $text = @()
PS> $text += "Hello"
PS> $text += "World"
PS> $text
Hello
World
PS> $text | Out-String
Hello
World

So, to construct multiline text throughout your script, start with @() to create an empty array, then add all the lines to this array using +=. When you are done, pipe the array to Out-String to get one multiline string. Easy.

Twitter This Tip!
ReTweet this Tip!