How to handle backslash character in PowerShell -replace string operations?

 ̄綄美尐妖づ 提交于 2019-11-30 09:10:31

问题


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?


回答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')


来源:https://stackoverflow.com/questions/37001694/how-to-handle-backslash-character-in-powershell-replace-string-operations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!