0

I have a requirement where my string is of format as below:

<?define BuildNumber = "8314" ?>

I am using below powershell script in TFS 2017 build template to replace the build number value:

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

This gives output like <?define BuildNumber = " 27994 " ?> which is incorrect as I do not want spaces in the value. When I tried using below code, it does not work.

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

Output : <?define $27994 ?>

I tried all combinations but cannot get the quotations to work correctly. Please suggest a solution.

Mustafa
  • 202
  • 3
  • 14
  • 1
    Possible duplicate of [Why is powershell -replace operator not properly including all characters captured in the capture group?](https://stackoverflow.com/questions/53215162/why-is-powershell-replace-operator-not-properly-including-all-characters-captur) – user4003407 Dec 13 '18 at 10:47
  • 1
    `-Replace '(?<=BuildNumber\s*=\s*")\d*(?="\s*)', $num` – Olaf Dec 13 '18 at 10:51
  • @Olaf This is a solution. I was actually not able to understand why it was not working in the original code. – Mustafa Dec 13 '18 at 11:30

1 Answers1

2

Use curly braces to "escape" group number

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

A little clarification about why the original code doesn't work: after $num variable has been resolved the replace string became $127994$2. That means that the -replace operator is trying to find group $127994 which obviously does not exist. When we add curly braces it becomes ${1}27994$2 which is completely legit.

montonero
  • 1,363
  • 10
  • 16