Create a String

1. Problem

You want to create a variable that holds text.

2. 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'



3. 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).

For a detailed explanation of the escape sequences and replacement rules inside PowerShell strings, see “Strings” in Appendix A.

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:

Code View: Scroll / Show All

        $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 single-quoted 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. If you intend to create large reports, see Section 5.13, “Generate Large Reports and Text Streams.”

Tags: , , , , , , , ,