Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

How to replace literal strings in Powershell?

I have this line of code that I can't seem to backslash correctly:

(Get-Content prefs.js) | %{$_ -replace "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)","Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.2 Safari/537.36"} | Set-Content prefs.js


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

... | %{$_.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:

[PS]> "Hello" -replace 'll','$_'                  # Doesn't work!
HeHelloo

[PS]> "Hello".Replace('ll','$_')                  # WORKS!
He$_o

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...