Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading