0

I'm trying to execute the following Powershell script during the Jenkins build process:

Write-Host ==================================================
Write-Host Setting Version to $env:Version BEGIN
(Get-Content .\MyFile.js) -replace '"Version"\s*:\s*".*"', '"Version" : "$env:Version"' | Out-File .\MyFile.js
Write-Host Setting Version to $env:Version COMPLETE
Write-Host ==================================================

The first and last instances of $env:Version get substituted correctly. I see the output

==================================================
Setting Version to 1.2.3.4 BEGIN
Setting Version to 1.2.3.4 COMPLETE
==================================================

But the second instance of $env:Version does not get replaced in MyFile.js. When I open up MyFile.js, I see the following:

"Version" : "$env:Version",

How can I pass this environment variable to the Get-Content command? Is it something about regular expressions (triggered by -replace) that is preventing the substitution from happening?

0

1 Answer 1

3

You have that string in single quotes which wont allow the variable to expand.

'"Version" : "$env:Version"'   

Could be this instead. We use backticks to escape the quotes so the interpreter does not eat them up. Might need a subexpression as well.

"`"Version`" : `"$($env:Version)`""

or as per Etan Reisner's solution

('"Version" : "{0}"' -f $env:version)

Could even improve on that -replace as well I think and make it cleaner. Use a capture group to hold the first part of the string, as $1, since it will remain the same. The use the format operator to add in the $env:version so we don't need a subexpression.

-replace '("Version"\s*:\s*)".*"',('$1"{0}"' -f $env:version)
Sign up to request clarification or add additional context in comments.

4 Comments

Use of ('"Version" : "{0}"' -f $env:version) might be better here (to avoid needing the backticks, etc.).
Backticks don't seem to be helping. I'll try to implement Etan's suggestion, though.
Hmm thats odd. I just tried it again and it was working. Have a look at my second solution as well.
So @EtanReisner 's suggestion worked - Thanks! The final command that I used was: (Get-Content .\MyFile.js) -replace '"Version"\s*:\s*".*"', ('"Version" : "{0}"' -f $env:Version) | Out-File .\MyFile.js

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.