I am trying to write a PowerShell script to update my .nuspec
file (nuget depdency) to the latest build version. I am having trouble with the wildcards though.
So I want to replace the version number of this line
<dependency id="MyCompany.Common" version="1.0.0.0" />
to a new version number, i.e. version 2.2.2.2
<dependency id="MyCompany.Common" version="2.2.2.2" />
My current place method looks like this. Note I need a wildcard as I have multiple nuget packages in the solution I need to replace, all follow the format of MyCompany.PackageName
$filecontent -replace 'id="MyCompany.*" version="*"', "$Version" | Out-File $file
But this actually ends up creating
<dependency 2.2.2.21.0.0.0" />
How do I modify my regex to ensure it replaces the version number component only?
You don't need to assign a string to a variable to replace text in a string. Instead, you can invoke the replace() method directly on the string like: 'hello world'. replace('hello','hi') . The tutorial is using a variable for convenience.
If you are using the PowerShell replace() method, you can chain replace() method as many times to replace the multiple characters in the PowerShell string. Like the replace() function, you can also chain PowerShell replace operator if you have multiple instances of characters to replace with.
Replacing characters or words in a string with PowerShell is easily done using either the replace method or -replace operator. When working with special characters, like [ ], \ or $ symbols, it's often easier to use the replace() method than the operator variant.
You can use them to create word patterns in commands. Wildcard expressions are used with the -like operator or with any parameter that accepts wildcards. In this case, the asterisk ( * ) wildcard character represents any characters that appear before the .
Replace with
$filecontent -replace 'id="MyCompany(.*?)" version=".*?"', "id=`"MyCompany`$1`" version=`"$Version`"" | Out-File $file
I went with a simple use of a capture group so I don't lose the specificity of your regex, matches only strings with 'MyCompany.*' in id, but doesnt add a lot of complexity. I capture everything up to the opening quote in version and replace whatever is before the next quote with the new version number.
$test='<dependency id="MyCompany.Common" version="1.0.0.0" />'
$newVersion='2.2.2.2'
$test -replace "(id=`"MyCompany`..*`" version=)`"[^`"]*","`$1`"$newVersion"
<dependency id="MyCompany.Common" version="2.2.2.2" />
Tested in PS 4.0
Powershell oddities and fragile bits include:
backtick to escape instead of \
regex must be in "double quotes"
must either use single quotes or escapes to have capture groups work in the replacement string
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With