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?
Can you give us a bit more details about your code? (To escape the backslash you need to use double backslash : "\\" instead of "\".)
This means that if you hard code a Distinguished Name in PowerShell, and the string is enclosed in double quotes, any embedded double quotes must be escaped first by a backtick "`", and then by a backslash "\".
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.
The examples in the table are based on the current working directory being set to C:\Windows. The backslash indicates that the drive root of the current working location should be used.
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')
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 \
.\
'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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With