Home » How to Escape Single Quotes in PowerShell

How to Escape Single Quotes in PowerShell

You can escape a single quote (‘) in a string or variable by using the two single quotes in PowerShell.

The following methods show how you can do it with syntax.

Method 1: Escaping single quotes in a single-quoted string

$originalString = 'It''s a single-quoted string.'

Write-Output $originalString

In this example, it uses two single quotes to escape a single quote in a string.

Method 2: Escaping single quotes in a double-quoted string

$originalString = "It's a single-quoted string."

Write-Output $originalString

In this example, you don’t need to escape single quotes if a string is enclosed in double quotes.

Method 3: Escaping single quotes in a Variable

$originalString = "It's a single-quoted string."

$modifiedString = $originalString -replace "'", "''"

Write-Output $modifiedString

In this example, it escapes single quotes by replacing them with two single quotes.

The following examples show how to use these methods in practical application.

Escaping Single Quotes in a Single-Quoted String

The simplest way to escape a single quote in a single-quoted string is by using the two single quotes.

Here’s how you can do it.

$string = 'It''s a single-quoted string.'
Write-Output $string

Output:

It's a single-quoted string.

In this example, the $string variable contains the single quotes in a single-quoted string. To escape single quotes, we have used two single quotes.

Finally, the Write-Output cmdlet outputs the string content.

Escaping Single Quotes in a Double-Quoted String

You don’t need to escape single quotes if the string is enclosed in double quotes.

$string = "It's a single-quoted string."
Write-Output $string

Output:

It's a single-quoted string.

Escaping Single Quotes in a Variable

You can escape single quotes in a variable by replacing it with two single quotes. Here’s how you can do it.

$originalString = "It's a single-quoted string."

$modifiedString = $originalString -replace "'", "''"

Write-Output $modifiedString

Output:

It''s a single-quoted string.

In this PowerShell script, a string variable $originalString contains single quotes.

We used the -replace operator to replace single quotes with two single quotes and store it in the $modifiedString variable.

Finally, the Write-Output cmdlet outputs the variable value on the terminal.

Conclusion

I hope the above article on escaping single quotes in PowerShell is helpful to you.

You can find more topics about Active Directory tools and PowerShell basics on the ActiveDirectoryTools home page.