使用 powershell 查找并替换文件中的 $VARIABLE$

bja*_*ven 5 powershell

我正在制作一个简单的 powershell 脚本来替换我们环境中的 SubWCRev。所以我有很多包含变量的模板文件等等$WCREV$

不过,我无法对这些变量进行简单的查找和替换。我无法正确转义 $ 字符。

查找和替换很简单;

function FindAndReplace {
param(
    [string]$inputFile, 
    [string]$outputFile,
    [string]$findString, 
    [string]$replaceString)
    (Get-Content $inputFile) | foreach {$_ -replace $findString, $replaceString} |
    Set-Content $outputFile
}
Run Code Online (Sandbox Code Playgroud)

我已经尝试了许多 $findString 的替代方案..

尝试过;

$findString = '$WCREV$'
$findString = '`$WCREV`$'
$findString = "`$WCREV`$"
$findString = "$WCREV$" 
Run Code Online (Sandbox Code Playgroud)

无法使任何工作发挥作用。如果我尝试只使用 WCREV,它会替换它,但是当然,我会剩下 $。我想我可以修改我的模板,但这似乎是一个愚蠢的小问题,所以它可能是可行的,对吧?

Mat*_*att 5

您正在使用-replace支持正则表达式的。$是那里的线锚点的末端。如果您不需要正则表达式,则只需使用字符串方法替换即可。

$findString = '$WCREV$'
(Get-Content $inputFile) | foreach {$_.replace($findString,$replaceString)}
Run Code Online (Sandbox Code Playgroud)

要使用$findString代码制作原始文件,您需要使用正则表达式转义字符,这是 PowerShell 的反斜杠,就像您尝试的那样。单引号对于防止 PowerShell 尝试将字符串扩展为变量非常重要。以下任一方法都可以,但我的第一个片段是我建议的。

$findString = '\$WCREV\$'
$findString = [regex]::Escape('$WCREV$')
Run Code Online (Sandbox Code Playgroud)