简体   繁体   English

在-replace中转义双引号

[英]Escape double quotes in -replace

I have a PowerShell script to replace DEV web config entries with QA values. 我有一个PowerShell脚本,可以用QA值替换DEV Web配置条目。

So far good, but now I have some values with double quotes: 到目前为止还不错,但是现在我有一些带有双引号的值:

   (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

I get parser error when I run. 运行时出现解析器错误。 If I change double quote to single quote like 如果我将双引号更改为单引号,例如

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

Since -replace is using regex, you should use [regex]::Escape to escape your characters (or use $_.Replace() instead): 由于-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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM