如何更换" \"用" \\"使用PowerShell?

时间:2014-12-13 14:51:55

标签: powershell powershell-v3.0

我有一个包含路径的字符串。

$Paths = "Myfolder\Mysubfolder"

我需要替换它们,如“Myfolder \ Mysubfolder”

$Paths -replace "\","\\"失败,因为正则表达式无法找到并替换“\”。

如何更换?

2 个答案:

答案 0 :(得分:5)

您可以使用不使用此类正则表达式的.Replace()

$Paths = "Myfolder\Mysubfolder"
$Paths.replace('\','\\')

要使用-replace,您需要转义斜杠,因为它是正则表达式,匹配且$1和{{1}之外的替换使用替换组的...等等。

$2

两者的结果是:

$Paths -replace '\\','\\'

答案 1 :(得分:0)

我在想=作业是必需的吗?

$Paths = "Myfolder\Mysubfolder"
write-Host "debug ..... : $Paths"
$Paths = $Paths.Replace("\","\\")
write-Host "debug ..... : $Paths"

这给出了:

debug ..... : Myfolder\Mysubfolder
debug ..... : Myfolder\\Mysubfolder