Place Special Characters in a String

1. Problem

You want to place special characters (such as tab and newline) in a string variable.

2. Solution

In an expanding string, use PowerShell’s escape sequences to include special characters such as tab and newline.

        PS >$myString = "Report for Today'n----------------"
        PS >$myString
        Report for Today
        ----------------



3. Discussion

As discussed in Section 5.1, “Create a String,” PowerShell strings come in two varieties: literal (or nonexpanding) and expanding strings. A literal string uses single quotes around its text, while an expanding string uses double quotes around its 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 $ENV: SystemRoot) and escape sequences (such as ‘n) with their values (such as the SystemRoot environment variable and the newline character).

Unlike many languages that use a backslash character (\) for escape sequences, PowerShell uses a back-tick (’) character. This stems from its focus on system administration, where backslashes are ubiquitous in path names.

Tags: , , , , , , , , , , , , , , , ,