我有一个要求,我的字符串的格式如下:
<?define BuildNumber = "8314" ?>
我在TFS 2017构建模板中使用以下powershell脚本来替换构建号值:
$content = Get-Content -path "$(Build.SourcesDirectory)InstallCommonConstants.wxi"
$num = $(Build.BuildId)
$content -Replace '(BuildNumbers*=s*")d*("s*)', "`$1 $num `$2" | Out-File $(Build.SourcesDirectory)InstallCommonConstants.wxi
这会给出类似<?define BuildNumber = " 27994 " ?>
的输出,这是不正确的,因为我不希望在值中有空格。当我尝试使用以下代码时,它不起作用。
$content -Replace '(BuildNumbers*=s*")d*("s*)', "`$1$num`$2" | Out-File $(Build.SourcesDirectory)InstallCommonConstants.wxi
输出:<?define $27994 ?>
我尝试了所有的组合,但无法使报价正确发挥作用。请提出解决方案。
使用大括号"转义"组号
$content -Replace '(BuildNumbers*=s*")d*("s*)', "`${1}$num`$2" | Out-File $(Build.SourcesDirectory)InstallCommonConstants.wxi
关于为什么原始代码不起作用的一点澄清:在解析$num变量后,替换字符串变成了$127994$2。这意味着-replace-运算符正试图查找组$127994,而该组显然不存在。当我们添加大括号时,它变为${1}279942美元,这是完全合法的。