在 -replace 中转义双引号

Bil*_*lla 1 powershell command-line powershell-2.0

我有一个 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
Run Code Online (Sandbox Code Playgroud)

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

`-replace 'valwithdoublequote' 'valwithdoublequote' still I get parser error. How to escape this?
Run Code Online (Sandbox Code Playgroud)

Mar*_*ndl 5

由于-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
Run Code Online (Sandbox Code Playgroud)