【问题标题】:Powershell -replace command is replacing $_ string literal from within the replace stringPowershell -replace 命令正在替换替换字符串中的 $_ 字符串文字
【发布时间】:2017-03-06 22:29:06
【问题描述】:

我是 powershell 脚本的新手。 我尝试使用 powershell 主要版本 5 开发脚本。我的脚本的目标是用一些字符串替换模板文件中的几个字符串文字。请注意,其中一个字符串文字被替换为文件的内容。

$ReleaseScript =  Get-Content $SourceFile -Raw

(Get-Content $ChangeSetTemplatefile -Raw)  |  
 ForEach-Object {
$_  -replace '<insert_script_here>', $ReleaseScript  `
-replace '<username>'          , $UserName  
} 
| Set-Content $CSDestinationFile"

上述替换工作正常,除非 $ReleaseScript 中的文件内容本身有 $_。 有没有办法让转义字符避免替换替换字符串内容或任何其他方式来实现目标?

【问题讨论】:

  • single 引用的替换字符串中使用 $$。见regex reference。我不确定我是否完全理解这个问题,所以我不会将其发布为答案。
  • 呃,实际上,要替换字符串文字使用字符串替换方法:$_.replace('string1', 'string2')

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


【解决方案1】:

-replace 进行正则表达式匹配。您需要转义正则表达式特殊字符,例如:

$ReleaseScript =  Get-Content $SourceFile -Raw
$ReleaseScript =  [regex]::Escape($ReleaseScript)

例如

PS C:\> [regex]::Escape('$_')
\$_

(或者,作为@wOxxOm cmets,字符串文字替换为.Replace()字符串方法)

【讨论】:

    猜你喜欢
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 2013-12-08
    • 2012-04-26
    • 2023-04-11
    • 1970-01-01
    相关资源
    最近更新 更多