Question:
I have this code where I can’t seem to backslash the find/replace strings correctly:
1 2 3 4 5 |
$find = "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" $replace = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.2 Safari/537.36" Get-Content prefs.js | %{ $_ -replace $find, $replace } | Set-Content prefs.js |
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:
1 2 |
... | %{$_.Replace("string to replace", "replacement")} | ... |
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:
1 2 3 4 5 6 |
[PS]> "Hello" -replace 'll','$_' # Doesn't work! HeHelloo [PS]> "Hello".Replace('ll','$_') # WORKS! He$_o |