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

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


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')