24/7/365 Support

Create a Multiline or Formatted String in Windows PowerShell

Problem

You want to create a variable that holds text with newlines or other explicit formatting.

Solution

Use a PowerShell here string to store and work with text that includes newlines and other formatting information.

$myString = @" This is the first line of a very long string. A "here string" lets you to create blocks of text that span several lines. "@

Discussion

PowerShell begins a here string when it sees the characters @" followed by a newline. It ends the string when it sees the characters "@ on their own line. These seemingly odd restrictions allow you to create strings that include quote characters, newlines, and other symbols that you commonly use when you create large blocks of preformatted text.

These restrictions, while useful, can sometimes cause problems when you copy and paste PowerShell examples from the Internet. Web pages often add spaces at the end of lines, which can interfere with the

strict requirements of the beginning of a here string. If PowerShell produces an error when your script defines a here string, check that the here string does not include an errant space after its first quote character.

Like string literals, here strings may be literal (and use single quotes) or expanding (and use double quotes).

In addition to their usefulness in preformatted text variables, here strings also provide a useful way to temporarily disable lines in your script. Since PowerShell does not provide a firstclass multiline comment, you can use a here string as you would use a multiline comment in other scripting or programming languages. Example 51 demonstrates this technique.

Example 51. Using here strings for multiline comments

## This is a regular comment $null = @" function MyTest {

Example 51. Using here strings for multiline comments (continued)

"This should not be considered a function" }

$myVariable = 10; "@

## This is regular script again

Using $null for the variable name tells PowerShell to not retain the information for your later use.

Help Category:

Get Windows Dedicated Server

Only reading will not help you, you have to practice it! So get it now.

Processor RAM Storage Server Detail
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 1 TB (HDD SATA) Configure Server
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 128 GB (SSD SATA) Configure Server
Intel Atom C2750 2.4 GHz 8c/8t 8 GB DDR3 1× 1 TB (HDD SATA) Configure Server
Intel Xeon E3-1230 v2 3.3 GHz 4c/8t 16 GB DDR3 1× 256 GB (SSD SATA) Configure Server
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 250 GB (SSD SATA) Configure Server

What Our Clients Say