Getting and replacing AssemblyVersion from AssemblyInfo.cs

I have a regular expression that I use (only in the test) to update AssemblyVersion from the AssemblyInfo.cs file. I am wondering, however, what is the best way to pull and replace this value from a .cs file would be?

Here is my best guess, which obviously doesn't work, but the general idea is in place. Hope for something more elegant.

 Get-Content $file | Foreach-Object{ $var = $_ if($var -contains "AssemblyVersion"){ $temp = [regex]::match($s, '"([^"]+)"').Groups[1].Value.Substring(0, $prog.LastIndexOf(".")+1) + 1234 $var = $var.SubString(0, $var.FirstIndexOf('"') + $temp + $var.SubString($var.LastIndexOf('"'), $var.Length-1)) } } 

EDIT

In the query, here is the line I want to update in AssemblyInfo:

 [assembly: AssemblyVersion("1.0.0.0")] 
+7
powershell
source share
1 answer

Not going to change your regular expression, but wants to show you the flow of what you can try.

 $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 each line and check if there is a corresponding line. When a match is found, the version is saved as the type [version] . Using this, we update the version as necessary. Then print the updated line. Unsuitable lines are displayed only as is.

The file is read, and since it is in parentheses, the handle is closed before the start of the pipeline process. This allows us to 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 work as you expected, since -contains is an array operator. -match would be preferable if you know that this is a regex support operator, so be careful with metacharacters. -like "*AssemblyVersion*" will also work and supports simple wildcards.

+15
source share

All Articles