Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape a backslash in Powershell

I'm writing a powershell program to replace strings using

-replace "$in", "$out"

It doesn't work for strings containing a backslash, how can I do to escape it?

like image 812
Zakaria Belghiti Avatar asked Apr 20 '16 15:04

Zakaria Belghiti


People also ask

How do you escape a slash in PowerShell?

If you use the [ADSI] accelerator, (or the equivalent [System. DirectoryServices. DirectoryEntry] class) or ADO in PowerShell, the forward slash character "/" must be escaped with the backslash "\" in Distinguished Names. The [ADSI] accelerator and ADO both use ADSI.

How do I escape a backslash?

The first two backslashes ( \\ ) indicate that you are escaping a single backslash character. The third backslash indicates that you are escaping the double-quote that is part of the string to match.

How do I get out of brackets in PowerShell?

The escape character in PS is the "back-tic" = `.


2 Answers

The -replace operator uses regular expressions, which treat backslash as a special character. You can use double backslash to get a literal single backslash.

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

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

That method escapes any characters that are special to regex with whatever is needed to make them a literal match (other special characters include .,$,^,(),[], and more.

like image 104
briantist Avatar answered Nov 01 '22 00:11

briantist


You'll need to either escape the backslash in the pattern with another backslash or use the .Replace() method instead of the -replace operator (but be advised they may perform differently):

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

Note that only the search pattern string needs to be escaped. The code -replace '\\','\\' says, "replace the escaped pattern string '\\', which is a single backslash, with the unescaped literal string '\\' which is two backslashes."

So, you should be able to use:

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

[Note: briantist's solution is better.]

However, if your pattern has consecutive backslashes, you'll need to test it.

Or, you can use the .Replace() string method, but as I said above, it may not perfectly match the behavior of the -replace operator:

PS C:\> 'a\sdf'.replace('a\\s', 'b')
a\sdf
PS C:\> 'a\sdf'.replace( 'a\s', 'b')
bdf
like image 21
Bacon Bits Avatar answered Oct 31 '22 22:10

Bacon Bits