如何使用 PowerShell 替换字符串中包含反斜杠 (\) 的文件内容?

How to replace the content of file containg backslash ( \ ) in its string using PowerShell?

我有一个包含多个占位符的配置文件,我想使用 PowerShell 将其替换为其他一些值,但下面的代码无法将 %WebClientPath%\www 替换为 $WebClientPath 变量中包含的值.它有这个路径“C:\IWeb\Demo\Main\UIPresentation\WebApp” 其中 %VirtualApplicationName%IMWeb

取代

我尝试从 %WebClientPath% 中删除 \www 并且成功了,但我希望 \www 也被替换。我认为这是因为反斜杠 ( \ )

[CmdletBinding()]
Param
(   
    [string]$PathofWebConfigFile="C:\Automate\Web.config"  ,
    [string]$VirtualApplicationName="IMWeb"  
)


# Code to get WebClient Path from PhysicalPath attribute.
$WebClientPath=(get-webapplication IMWeb).PhysicalPath


(Get-Content -Path "$PathofWebConfigFile") | ForEach-Object {$_ -Replace "%VirtualApplicationName%","$VirtualApplicationName"} | Set-Content -Path "$PathofWebConfigFile"
(Get-Content -Path "$PathofWebConfigFile") | ForEach-Object {$_ -Replace "%WebClientPath%\www","$WebClientPath"} | Set-Content -Path "$PathofWebConfigFile"


斜杠 \ 被双斜杠 \ 转义,试试这个:

"mypath\www" -replace "\www","\zzz"

此 cmdlet 会将 \www 替换为 \zzz

-replace 运算符是基于 RegEx 的,因此您必须

  • 转义作为 RegEX 指令的单个字符或
  • 如果事先不知道变量内容最好使用[Regex]::Escape()

您可以选择使用不基于 RegEx 的 String.Replace 方法:

$_.Replace("%WebClientPath%\www","$WebClientPath")