What is the literal escape character in Powershell?

Solution 1:

From help about_quoting_rules

To make double-quotation marks appear in a string, enclose the entire string in single quotation marks. For example:

'As they say, "live and learn."'

The output from this command is:

As they say, "live and learn."

You can also enclose a single-quoted string in a double-quoted string. For example:

"As they say, 'live and learn.'"

The output from this command is:

As they say, 'live and learn.'

To force Windows PowerShell to interpret a double quotation mark literally, use a backtick character. This prevents Windows PowerShell from interpreting the quotation mark as a string delimiter. For example:

"Use a quotation mark (`") to begin a string."

The output from this command is:

Use a quotation mark (") to begin a string.

Because the contents of single-quoted strings are interpreted literally, you cannot use the backtick character to force a literal character interpretation in a single-quoted string.

The use of the backtick character to escape other quotation marks in single quoted strings is not supported in recent versions of PowerShell. In earlier versions of PowerShell the backtick escape character could be used to escape a double quotation mark character within a single quoted string as detailed in the help about_quoting document that is available in those versions of PowerShell.

Solution 2:

The escape character in Powershell is the "`" (backward apostrophe/grave).

This can be used to escape quotes and also special characters (e.g., tab is `t).


Solution 3:

To compliment what has already been provided here, you should also know that you can escape a quote (single or double) with the quote itself. That means you can do this:

"Here's an example of a ""double-quoted string""."

and this:

'This time it''s ''single-quoted''.'

The advantage this syntax provides is simple: it's easier to type the same quote twice than it is to escape a quote with a backtick.


Solution 4:

single 'text' so it is treated as literal text, then escape any special characters using "\"

e.g. This string: "As they say, "live and learn."" Becomes this string 'As they say, \"live and learn.\"'

Tags:

Powershell