我正在使用-replace将路径从源更改为目标。但是我不确定如何处理\字符。例如:
$source = "\\somedir"
$dest = "\\anotherdir"
$test = "\\somedir\somefile"
$destfile = $test -replace $source, $dest
此操作后,$destfile 被设置为
"\\\anotherdir\somefile"
什么是正确的方式以避免结果中出现三条反斜杠?我正在使用-replace将路径从源更改为目标。但是我不确定如何处理\字符。例如:
$source = "\\somedir"
$dest = "\\anotherdir"
$test = "\\somedir\somefile"
$destfile = $test -replace $source, $dest
此操作后,$destfile 被设置为
"\\\anotherdir\somefile"
什么是正确的方式以避免结果中出现三条反斜杠?请尝试以下操作:
$source = "\\\\somedir"
在替换时,您只匹配了1个反斜杠,这使得路径开头有三个\\\
。
反斜杠是一个正则表达式
转义字符,因此\\
将被视为仅匹配一个\
而不是两个\\
。由于第一个反斜杠是转义字符而不是用于匹配的字符。
另一种处理反斜杠的方法是使用正则表达式
转义函数。
$source = [regex]::escape('\\somedir')
我在使用Test-Path
和Get-Item
处理带空格的UNC路径时遇到了问题,后来在这里找到了部分解决方法。而另一部分解决方法如下:
$OrginalPath = "\\Hostname\some\path with spaces"
$LiteralPath = $OriginalPath -replace "^\\{2}", "\\?\UNC\"
结果:
\\?\UNC\主机名\某个带空格的路径
为了完整起见,将其放入 Test-Path
中返回 true(假设该路径实际存在)。正如@Sage Pourpre所说,需要使用 -LiteralPath
:
Test-Path -LiteralPath $LiteralPath
或者
Get-Item -LiteralPath $LiteralPath
替换运算符 -replace
使用正则表达式。
^
表示字符串开头。\
是转义字符,因此我们使用 \
转义 \
。\
,所以使用 {2}
告诉正则表达式查找确切的 2 个 \
。除了使用 {2}
,你可以像@Richard所说的那样使用四个 \
。一个转义另一个。
在此处尝试一下。
[regex]::Escape()
是更安全的解决方案,因为它也会处理其他特殊字符(比如+
或者括号)。 - Ansgar Wiechers[regex]::Escape()
不能按预期工作。 - Ivan Popivanov