How to handle backslash character in PowerShell -replace string operations?

timanderson picture timanderson · May 3, 2016 · Viewed 42.4k times · Source

I am using -replace to change a path from source to destination. However I am not sure how to handle the \ character. For example:

$source = "\\somedir"
$dest = "\\anotherdir"

$test = "\\somedir\somefile"

$destfile = $test -replace $source, $dest

After this operation, $destfile is set to

"\\\anotherdir\somefile"

What is the correct way to do this to avoid the triple backslash in the result?

Answer

Richard picture Richard · May 3, 2016

Try the following:

$source = "\\\\somedir"

You were only matching 1 backslash when replacing, which gave you the three \\\ at the start of your path.

The backslash is a regex escape character so \\ will be seen as, match only one \ and not two \\. As the first backslash is the escape character and not used to match.

Another way you can handle the backslashes is use the regex escape function.

$source = [regex]::escape('\\somedir')