我有 powershell 文件,其中有如下变量声明行
[string] $global:myExePath = "\\myshare\code\scripts";
我想通过执行 powershell 脚本在运行时将 \\myshare\code\scripts
替换为 \\mynewshare\code1\psscript
。
我正在使用
获取内容$originalfile | ForEach-Object { $_ -replace "\\myshare\code\scripts", $mynewcodelocation.FullName } |设置内容($originalfile)
如果正在执行
{ $_ -replace "scripts", $mynewcodelocation.FullName }
它工作正常,但不适用于 { $_ -replace "\\myshare\code\scripts", $mynewcodelocation.FullName }
这里出了什么问题?
最佳答案
“\”是一种特殊的正则表达式字符,用于转义其他特殊字符。您需要将每个反斜杠加倍以匹配一个反斜杠。
-replace "\\\\myshare\\code\\scripts",$mynewcodelocation.FullName
当你不知道字符串的内容时,你可以使用 escape 方法来为你转义字符串:
$unc = [regex]::escape("\\myshare\code\scripts")
$unc
\\\\myshare\\code\\scripts
-replace $unc,$mynewcodelocation.FullName
关于powershell - 字符串替换在运行时在 powershell 脚本中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18811284/