Monday, January 9, 2012

Adding New Lines to Strings

 

PowerTip of the Day, from PowerShell.com:

 

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.

 

Thanks

No comments:

Post a Comment