powershellreplacebackslash

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


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?


Solution

  • 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 to use the Regex.Escape function from .NET, i.e:

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