Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

powershell - Get and Replace AssemblyVersion from AssemblyInfo.cs

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 pull and replace this value from the .cs file itself would be?

Here is my best guess which, obviously, isn't working but the general idea is in place. Was hoping for something a little 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

Per request here is the line I'm looking to update in the AssemblyInfo:

[assembly: AssemblyVersion("1.0.0.0")] 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Not really intending to change your regex but wanting to show you the flow of what you could be trying.

$path = "C:empest.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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...