Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save andykuszyk/1d6baa489a4dc03a1cee35c9f718671f to your computer and use it in GitHub Desktop.
Save andykuszyk/1d6baa489a4dc03a1cee35c9f718671f to your computer and use it in GitHub Desktop.
Increasing version numbers in project.json or AssemblyInfo.cs using Powershell

#Increasing version numbers in project.json or AssemblyInfo.cs using Powershell

As part of an automated deployment process, I needed to increase the minor version numbers stored in both project.json and AssemblyInfo.cs files. I achieved this with broadly similar powershell scripts.

Project.json

## This script picks up a json file, locates the version property and
## increases the most minor version number by 1.

Param([string]$jsonFilePath) ## The path to the json file to parse

## Method to increase the minor version number by 1.
function IncreaseVersionNumber
{
	$args[0] -match "(.*)\.[0-9]+\-\*$" > $null
	$majorVersion = $Matches[1]
	Write-Host "Major version is: $majorVersion"

	$args[0] -match "([0-9]+)\-\*$" > $null
	$minorVersion = $Matches[1]
	Write-Host "Minor version is: $minorVersion"

	$newMinorVersion = [convert]::ToInt32($minorVersion,10) + 1
	Write-Host "New minor version is $newMinorVersion"

	$newVersion = "$majorVersion.$newMinorVersion"
	Write-Host "New version is: $newVersion"

	return "$newVersion-*"
}

(Get-Content $jsonFilePath ) | foreach-object {
	if($_ -match '"version"\: "(.+)"')
	{
		Write-Host "$_ is a match"
		$newVersion = IncreaseVersionNumber $Matches[1]
		Write-Host "New version is: $newVersion"
		$_ -replace '"version"\: "(.+)"',[string]::Format('"version": "{0}"',$newVersion)
	}
	else
	{
		$_
	}
} | Set-Content $jsonFilePath

##AssemblyInfo.cs

## This script picks up an assemblyinfo file, locates the version property and
## increases the most minor version number by 1.

Param([string]$assemblyInfoPath) ## The path to the assemblyinfo file to parse

## Method to increase the minor version number by 1.
function IncreaseVersionNumber
{
	$args[0] -match "(.*)\.[0-9]+$" > $null
	$majorVersion = $Matches[1]
	Write-Host "Major version is: $majorVersion"

	$args[0] -match "([0-9]+)$" > $null
	$minorVersion = $Matches[1]
	Write-Host "Minor version is: $minorVersion"

	$newMinorVersion = [convert]::ToInt32($minorVersion,10) + 1
	Write-Host "New minor version is $newMinorVersion"

	$newVersion = "$majorVersion.$newMinorVersion"
	Write-Host "New version is: $newVersion"

	return "$newVersion"
}

(Get-Content $assemblyInfoPath -encoding UTF8) | foreach-object {
	if($_ -match '^\[assembly\: Assembly.*Version\("([0-9]\.[0-9]\.[0-9])"\)\]')
	{
		Write-Host "$_ is a match"
		$newVersion = IncreaseVersionNumber $Matches[1]
		Write-Host "New version is: $newVersion"
		$_ -replace '[0-9]\.[0-9]\.[0-9]',$newVersion
	}
	else
	{
		$_
	}
} | Set-Content $assemblyInfoPath -encoding UTF8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment