我正在使用 -replace 来更改从源到目标的路径.但是我不确定如何处理 \ 字符.例如:
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此操作后,$destfile 设置为
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?
推荐答案尝试以下操作:
$source = "\\\\somedir"替换时您只匹配了 1 个反斜杠,这为您提供了路径开头的三个 \\\.
You were only matching 1 backslash when replacing, which gave you the three \\\ at the start of your path.
反斜杠是一个 regex 转义字符,所以 \\ 将被视为,只匹配一个 \ 而不是两个 \\.由于第一个反斜杠是转义字符,不用于匹配.
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.
处理反斜杠的另一种方法是使用 regex 转义函数.
Another way you can handle the backslashes is use the regex escape function.
$source = [regex]::escape('\\somedir')更多推荐
如何在 PowerShell 中处理反斜杠字符
发布评论