I have this code where I can't seem to backslash the find/replace strings correctly:
$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.
You don't need to assign a string to a variable to replace text in a string. Instead, you can invoke the replace() method directly on the string like: 'hello world'. replace('hello','hi') . The tutorial is using a variable for convenience.
Replace Multiple Instance Strings Using the replace() Function in PowerShell. Since the replace() function returns a string, to replace another instance, you can append another replace() function call to the end. Windows PowerShell then invokes the replace() method on the original output.
You can also change directory in PowerShell to a specified path. To change directory, enter Set-Location followed by the Path parameter, then the full path you want to change directory to. If the new directory path has spaces, enclose the path in a double-quote (“”).
Use the -Replace Operator to Escape Special Characters in PowerShell. The -Replace operator replaces texts or characters in PowerShell. You can use it to remove texts or characters from the string. The -Replace operator requires two arguments: the string to find and the string to replace from the given input.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With