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.