在 -replace 中转义双引号

Escape double quotes in -replace

我有一个 PowerShell 脚本可以用 QA 值替换 DEV Web 配置条目。

到目前为止还不错,但现在我有一些带双引号的值:

   (Get-Content $targetFile) |
         Foreach-Object {              
            $_ -replace "<add key="Path" value="/DEV/Reports" />", "<add key="WebReportsPath" value="/QA/Reports" />" `
                -replace "<add key="EmpReport" value="/DEV/Emp/Reports" />", "<add key="EmpReport" value="/QA/Emp/Reports" />" `                                        
                -replace "olddatabase", "newdatabase"

         } |
         Set-Content $targetFile

我在 运行 时遇到解析器错误。如果我将双引号更改为单引号,例如

`-replace 'valwithdoublequote' 'valwithdoublequote' still I get parser error. How to escape this?

因为 -replace 使用正则表达式,你应该使用 [regex]::Escape 来转义你的字符(或者使用 $_.Replace()):

(Get-Content $targetFile) |
         Foreach-Object {              
            $_ -replace [regex]::Escape('<add key="Path" value="/DEV/Reports" />'), '<add key="WebReportsPath" value="/QA/Reports" />' `
                -replace [regex]::Escape('<add key="EmpReport" value="/DEV/Emp/Reports" />'), '<add key="EmpReport" value="/QA/Emp/Reports" />' `                                        
                -replace "olddatabase", "newdatabase"

         } |
         Set-Content $targetFile