Search code examples
powershellescaping

Excape multiple $ characters in string in PowerShell script


I have this PowerShell code, which should be a simple replace, but it's not doing what I'm expecting.

$Text = "This is so$me! password with @special #characters$."

$Pattern = [regex]::Escape('$')
$CleanText = $Text -replace $Pattern, '`$'

Write-Host $CleanText

This returns the output:

  • This is so! password with @special #characters`$.

Notice how this does not add a backtick in front of the first $ character. But it does work for the last one. PowerShell reads $me in the string as a variable and for some reason it completely removes it.

I also tried the below, with the same result:

$Text = "This is so$me! text with @special #characters$."

$CleanText = $Text -replace '\$', '`$'

Write-Host $CleanText

Solution

  • The problem with the snippet you've posted occurs in the very first statement:

    $Text = "This is so$me! password with @special #characters$."
    

    String literals defined using double-quotes " are interpreted as expandable by PowerShell's parser, so $me will have already been evaluated by the time you reach the -replace operation.

    Use single-quote marks to define a verbatim string literal expression:

    $Text = 'This is so$me! password with @special #characters$.'
    

    See the about_Quoting_Rules help topic for more information about the behavior of different string literal expressions in PowerShell