Excape multiple $ characters in string in PowerShell script

  Kiến thức lập trình

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

LEAVE A COMMENT