在字符串替换中使用变量 - Windows powershell

Use variables in string replace - Windows powershell

我有一个要求,我的字符串格式如下:

<?define BuildNumber = "8314" ?>

我在 TFS 2017 构建模板中使用以下 powershell 脚本来替换构建编号值:

$content = Get-Content -path "$(Build.SourcesDirectory)\Install\Common\Constants.wxi"
$num  = $(Build.BuildId)
$content -Replace '(BuildNumber\s*=\s*")\d*("\s*)', "` $num `" |  Out-File $(Build.SourcesDirectory)\Install\Common\Constants.wxi

这给出了类似 <?define BuildNumber = " 27994 " ?> 的输出,这是不正确的,因为我不希望值中有空格。 当我尝试使用以下代码时,它不起作用。

$content -Replace '(BuildNumber\s*=\s*")\d*("\s*)', "`$num`" |  Out-File  $(Build.SourcesDirectory)\Install\Common\Constants.wxi

输出:<?define 994 ?>

我尝试了所有组合,但无法使引号正常工作。请提出解决方案。

用大括号给"escape"组号

$content -Replace '(BuildNumber\s*=\s*")\d*("\s*)', "`$num`" | Out-File $(Build.SourcesDirectory)\Install\Common\Constants.wxi

关于原始代码为何不起作用的一点说明:解析 $num 变量后,替换字符串变为 $127994$2。这意味着 -replace 运算符试图找到显然不存在的组 $127994。当我们添加花括号时,它变成 ${1}27994$2 这是完全合法的。