PowerShell Escape Sequences

Escape sequences are used to represent certain characters within a string, which would otherwise not be possible to include. In PowerShell, escape sequences start with a back quote (`), which is then followed by one or more characters.

As previously discussed, a message can be written out to the console using the ‘Write-Host’ cmdlet.

Write-Host "This is a string."

This writes out the message, ‘This is a string’, to the console. As can be seen in the above code, the message is contained in double quotes. In order to get a double quote to actually appear in the message within the console, an escape sequence needs to be used.

Write-Host "This is a string containing `"double quotes`"."

Here, a back quote is placed before the double quote in order to get it to appear in the message.

This is a string containing "double quotes".

As well as using an escape sequence for printable characters, such as double quotes, they can also be used for non-printable characters, such as including a new line within a string.

Write-Host "This is a string containing`na new line."

The escape sequence ‘`n’ is used within this message to force part of it to appear on a new line.

This is a string containing
a new line.

Below is a table containing some of the escape sequences that are available in PowerShell.

Escape
Sequence
Description
`0 The null character. Often used as a record separator.
`a The alert character. Generates a beep when displayed in the console.
`b The backspace character. The previous character remains in the string but is overwritten when displayed in the console.
`e The escape character. Marks the beginning of an ANSI escape sequence such as "`e[2J".
`f A form feed. Creates a page break when printing on most printers.
`n A new line.
`r A carriage return. New lines in PowerShell are indicated entirely by the `n character, so this is rarely required.
`t A horizontal tab.
`u{hex-code} A Unicode character literal. Creates a character represented by the specified hexadecimal Unicode code point, such as 'u{2265} for the greater than or equal to character.
`v A vertical tab.
`any other character The specified character, taken literally, such as `" for a double quote.