How to replace literal strings in Powershell?

Question:

I have this code where I can’t seem to backslash the find/replace strings correctly:

The $find value isn’t being replaced by the $replace value when this is run.

Answer:

It looks like you deal with literal strings. Do not use the -replace operator
which deals with regular expressions. Use the Replace method:

Alternatively, if you still want to use -replace then also use [regex]::Escape(<string>). It will do the escaping for you.

Example: replacing text literally with “$_”

Compare the results of the following, showing what can happen if you use an automatic variable in a regex replacement:

Source:

How to replace literal strings in Powershell? by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply