Last active
November 3, 2022 22:01
-
-
Save bcnzer/f8d50699c5bf7614923bff733662cb1a to your computer and use it in GitHub Desktop.
Powershell script for generating a version number and inserting it into the csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$csprojPath = $args[0] # path to the file i.e. 'C:\Users\ben\Code\csproj powershell\MySmallLibrary.csproj' | |
$newVersion = $args[1] # the build version, from VSTS build i.e. "1.1.20170323.1" | |
Write-Host "Starting process of generating new version number for the csproj" | |
$splitNumber = $newVersion.Split(".") | |
if( $splitNumber.Count -eq 4 ) | |
{ | |
$majorNumber = $splitNumber[0] | |
$minorNumber = $splitNumber[1] | |
$revisionNumber = $splitNumber[3] | |
# I need to keep my build number under the 65K int limit, hence this hack of a method | |
$myBuildNumber = (Get-Date).Year + ((Get-Date).Month * 31) + (Get-Date).Day | |
$myBuildNumber = $majorNumber + "." + $minorNumber + "." + $myBuildNumber + "." + $revisionNumber | |
$filePath = $csprojPath | |
$xml=New-Object XML | |
$xml.Load($filePath) | |
$versionNode = $xml.Project.PropertyGroup.Version | |
if ($versionNode -eq $null) { | |
# If you have a new project and have not changed the version number the Version tag may not exist | |
$versionNode = $xml.CreateElement("Version") | |
$xml.Project.PropertyGroup.AppendChild($versionNode) | |
Write-Host "Version XML tag added to the csproj" | |
} | |
$xml.Project.PropertyGroup.Version = $myBuildNumber | |
$xml.Save($filePath) | |
Write-Host "Updated csproj "$csprojPath" and set to version "$myBuildNumber | |
} | |
else | |
{ | |
Write-Host "ERROR: Something was wrong with the build number" | |
} |
Thanks for posting this script, it saved me the time of writing it from scratch.
Changes not reflected on build process if script triggered from Pre-build event. MSBuild didn't notice *.csproj file changes on the fly. How to resolve that?
$xml.Project.PropertyGroup might require index[0] to avoid set error because there might be several nodes PropertyGroup in your csproj
I use:
$xml.Project.PropertyGroup[0].FileVersion = $newVersion
on my project
God bless you ;)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I updated the above script to create the version tag if it doesn't exist. Realized that if you have a new project and haven't changed the version number in the properties > package tab, the version tag won't exist in the XML doc. VS assumes that, since it doesn't exist, it's 1.0.0. I've also written a new blog post to show how to support .NET Core 2.0 and .NET Standard 2.0