I have a regex I\'m using (in test only) to update the AssemblyVersion
from the AssemblyInfo.cs
file. I\'m wondering, however, what the best way to
Not really intending to change your regex but wanting to show you the flow of what you could be trying.
$path = "C:\temp\test.txt"
$pattern = '\[assembly: AssemblyVersion\("(.*)"\)\]'
(Get-Content $path) | ForEach-Object{
if($_ -match $pattern){
# We have found the matching line
# Edit the version number and put back.
$fileVersion = [version]$matches[1]
$newVersion = "{0}.{1}.{2}.{3}" -f $fileVersion.Major, $fileVersion.Minor, $fileVersion.Build, ($fileVersion.Revision + 1)
'[assembly: AssemblyVersion("{0}")]' -f $newVersion
} else {
# Output line as is
$_
}
} | Set-Content $path
Run for every line and check to see if the matching line is there. When a match is found the version is stored as a [version]
type. Using that we update the version as needed. Then output the updated line. Non-matching lines are just outputted as is.
The file is read in and since it is in brackets the handle is closed before the pipeline starts to process. This lets us write back to the same file. Each pass in the loop outputs a line which is then sent to set-content
to write back to the file.
Note that $var -contains "AssemblyVersion"
would not have worked as you expected as -contains
is an array operator. -match
would be preferable as long as you know that it is a regex supporting operator so be careful for meta-characters. -like "*AssemblyVersion*"
would also work and supports simple wildcards.