How to handle backslash character in PowerShell -replace string operations?
Solution 1
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')
Solution 2
I came here after having issues with Test-Path
and Get-Item
not working with a UNC path with spaces. Part of the problem was solved here, and the other part was solved as follows:
$OrginalPath = "\\Hostname\some\path with spaces"
$LiteralPath = $OriginalPath -replace "^\\{2}", "\\?\UNC\"
Result:
\\?\UNC\Hostname\some\path with spaces
For completeness, putting this into Test-Path
returns true (assuming that path actually exists). As @Sage Pourpre says, one needs to use -LiteralPath
:
Test-Path -LiteralPath $LiteralPath
or
Get-Item -LiteralPath $LiteralPath
The replacement operator -replace
uses regex.
-
^
means start of string. -
\
is the escape character, so we escape the\
with a\
. - As we have two
\
's we tell regex to look for exactly 2 occurrences of\
using{2}
.
Instead of using {2}
, you can do what @Richard has said and use four \
. One escapes the other.
Give it a try here.
Related videos on Youtube
timanderson
Updated on July 05, 2022Comments
-
timanderson almost 2 years
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?
-
Ansgar Wiechers about 8 years
[regex]::Escape()
is the safer solution, because it will handle other special characters (like+
or parentheses) as well. -
timanderson about 8 yearsthanks, this worked though I used the regex solution
-
Ivan Popivanov over 6 years
[regex]::Escape()
doesn't work as expected for paths containing '.'