Skip to main content

Create a String in PowerShell

Problem

You want to create a variable that holds text.

Solution

Use PowerShell string variables to give you a way to store and work with text.

To define a string that supports variable expansion and escape characters in its definition, surround it with double quotes:

$myString = "Hello World"

To define a literal string (that does not support variable expansion or escape characters), surround it with single quotes:

$myString = 'Hello World'

Discussion

String literals come in two varieties: literal (nonexpanding) and expanding strings. To create a literal string, place single quotes ($myString = 'Hello World') around the text. To create an expanding string, place double quotes ($myString = "Hello World") around the text.

In a literal string, all the text between the single quotes becomes part of your string. In an expanding string, PowerShell expands variable names (such as $myString) and escape sequences (such as `n) with their values (such as the content of $myString and the newline character, respectively).

One exception to the “all text in a literal string is literal” rule comes from the quote characters themselves. In either type of string, PowerShell lets you to place two of that string’s quote characters together to add the quote character itself:

$myString = "This string includes ""double quotes"" because it combined quote characters." $myString = 'This string includes ''single quotes'' because it combined quote characters.'

This helps prevent escaping atrocities that would arise when you try to include a single quote in a singlequoted string. For example:

$myString = 'This string includes ' + "'" + 'single quotes' + "'"

This example shows how easy PowerShell makes it to create new strings by adding other strings together. This is an attractive way to build a formatted report in a script but should be used with caution.

Due to the way that the .NET Framework (and therefore PowerShell) manages strings, adding information to the end of a large string this way causes noticeable performance problems. Create and manipulate strings efficiently with PowerShell on a United Kingdom Dedicated Server, providing dedicated resources, reliable performance, and full administrative control for running scripts and managing server-side applications.

Help Category