【问题标题】:How to replace the content of file containg backslash ( \ ) in its string using PowerShell?如何使用 PowerShell 替换其字符串中包含反斜杠 (\) 的文件的内容?
【发布时间】:2018-10-13 23:58:09
【问题描述】:

我有一个包含多个占位符的配置文件,我想使用 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"

【问题讨论】:

  • 你试过转义“\”字符吗?
  • 我确实尝试过类似的方法,但没有成功 (Get-Content -Path "$PathofWebConfigFile") | ForEach-Object {$_ -替换 "`\www",""} |设置内容-路径“$PathofWebConfigFile”
  • 让我知道在这种情况下使用 RegEx Escape 是否有帮助?

标签: xml powershell powershell-2.0 powershell-3.0 powershell-4.0


【解决方案1】:


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

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

此 cmdlet 会将 \www 替换为 \zzz。

【讨论】:

    【解决方案2】:

    -replace 运算符是基于正则表达式的,所以你必须要么

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

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

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

    【讨论】:

      猜你喜欢
      • 2018-01-29
      • 2018-09-25
      • 2021-06-17
      • 2023-03-20
      • 1970-01-01
      • 2018-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多