PowerShell by Patrik

Escaping $ in PowerShell Strings: Simple Ways That Always Work

When you write PowerShell scripts, strings may look simple at first. But sooner or later, you will face a small surprise: the $ character. In PowerShell, $ is special because it starts a variable. If you want to keep $ as plain text, for example inside JSON, you must escape it correctly. This short guide shows clear and safe ways to do that.

Why $ Needs Attention

In double-quoted strings, PowerShell tries to replace $name with the value of the variable. This is called variable expansion. If the variable does not exist, the result may be empty or wrong. That is why escaping $ is important when you want the literal text.

The Best Option: Single Quotes

Single-quoted strings do not expand variables. This makes them perfect for JSON and other text formats.

$body = '{"name": "$test"}'

This produces exactly:

{"name": "$test"}

Escaping $ in Double Quotes

If you must use double quotes, escape $ with the backtick character.

$body = "{""name"": ""`$test""}"

Using Here-Strings for Readability

Here-strings are great for larger text blocks. To keep $ literal, use the single-quoted version.

$body = @'
{"name": "$test"}
'@

Key Takeaway

If you do not need variable replacement, always prefer single quotes. They are cleaner, safer, and easier to read. Double quotes should be used only when variable expansion is required.

PowerShell
strings
json
scripting
automation

Comments