Define Multiline Text

by Aug 6, 2015

When you need to define multiline text, in PowerShell you typically use here-strings like this:

$text = @"
  I am safe here
  I can even use "quotes"
"@

$text | Out-GridView

The important thing to note is that the delimiters include (invisible) carriage returns. There must be one at the end of the starting tag, and one before the closing tag.

A highly unusual alternative for some distinct scenarios can be the use of a script block instead:

$text = {
  I am safe here
  I can even use "quotes"
}

$text.ToString() | Out-GridView 

The color coding is different, though, and you need to convert the script block to a string. This limits the usefulness because a script block is some piece of PowerShell code, and it gets parsed. So you can only enclose text that won't confuse the parser.

This is an example of invalid use, producing a syntax error because of the unbalanced quotes:

$text = {
  I am safe here 
  I can even use "quotes
}
 
$text.ToString() | Out-GridView 

Twitter This Tip! ReTweet this Tip!