Passing string included dollar signs to -Replace Variable

后端 未结 4 454
心在旅途
心在旅途 2021-01-18 07:58

I am trying to replace a sentence in .config file using powershell.

${c:Web.config} = ${c:Web.config} -replace

\'$BASE_PATH$\\

4条回答
  •  离开以前
    2021-01-18 08:40

    For those unfamiliar with the distinction, it is important not to confuse the backtick character (`) with the single-quotation character (') in these escapes. For example:

    [SUCCESS] Double quotes as container with backslash-backtick as escape:

    PS C:\Temp> 'What is $old?' | ForEach-Object {$_ -replace "\`$old", "(New)"}
    What is (New)?
    PS C:\Temp>
    

    [FAIL] Double quotes as container with backslash-apostrophe as escape:

    PS C:\Temp> 'What is $old?' | ForEach-Object {$_ -replace "\'$old", "(New)"}
    What is $old?
    PS C:\Temp>
    

    [SUCCESS] Single quotes as container with simple backslash as escape:

    PS C:\Temp> 'What is $old?' | ForEach-Object {$_ -replace '\$old', "(New)"}
    What is (New)?
    PS C:\Temp>
    

    [FAIL] Single quotes as container with backslash-backtick as escape:

    PS C:\Temp> 'What is $old?' | ForEach-Object {$_ -replace '\`$old', "(New)"}
    What is $old?
    PS C:\Temp>
    

    Overall, the easiest option may be to use single quotes as the container and a single backslash as the escape: '\$old'

提交回复
热议问题