Avoiding Backslash in Powershell

I am writing powershell program to replace strings using

-replace "$in", "$out"

This doesn't work for backslash strings, how can I avoid them?

+4
source share
2 answers

The operator -replaceuses regular expressions that treat backslashes as special characters. You can use double backslash to get a literal backslash.

In your case, since you are using variables, I assume that you will not know the contents at design time. In this case, you should run it through [RegEx]::Escape():

-replace [RegEx]::Escape($in), "$out"

, , , , ( ., $, ^, (), [] .

+7

, .Replace() -replace ( , -):

PS C:\> 'asdf' -replace 'as', 'b'
bdf
PS C:\> 'a\sdf' -replace 'a\s', 'b'
a\sdf
PS C:\> 'a\sdf' -replace 'a\\s', 'b'
bdf
PS C:\> 'a\sdf' -replace ('a\s' -replace '\\','\\'), 'b'
bdf

, . -replace '\\','\\' : " '\\', , '\\', ".

, :

-replace ("$in" -replace '\\','\\'), "$out"

[: briantist solution .]

, , .

.Replace(), , , -replace:

PS C:\> 'a\sdf'.replace('a\\s', 'b')
a\sdf
PS C:\> 'a\sdf'.replace( 'a\s', 'b')
bdf
+5

All Articles