It is surprising that the System.Version
type doesn't support methods for incrementing the components of a version number (neither does the the PowerShell Core-only System.Management.Automation.SemanticVersion
type).
Here's a PSv5+ solution:
$versionString = '1.2.0'
$version = [version] $versionString
$versionStringIncremented = [string] [version]::new(
$version.Major,
$version.Minor,
$version.Build + 1
)
# $versionStringIncremented now contains '1.2.1'
If you wanted to wrap that up in a function that allows incrementing any of the components, while setting all lower components to 0
or, in the case of .Revision
, to undefined (reported as -1
):
function Increment-Version {
param(
[Parameter(Mandatory)]
[version] $Version
,
[ValidateSet('Major', 'Minor', 'Build', 'Revision')]
[string] $Component = 'Revision'
)
$useRevision = $Version.Revision -ne -1 -or $Component -eq 'Revision'
$Major, $Minor, $Build, $Revision =
$Version.Major, $Version.Minor, $Version.Build, $Version.Revision
switch ($Component) {
'Major' { $Minor = $Build = 0 }
'Minor' { $Build = 0 }
}
Set-Variable $Component (1 + (Get-Variable -ValueOnly $Component))
if ($useRevision) {
[version]::new(
$Major,
$Minor,
$Build,
$Revision
)
} else {
[version]::new(
$Major,
$Minor,
$Build
)
}
}
Your command would then simplify to:
# -> '1.2.1'
$versionStringIncremented = [string] (Increment-Version 1.2.0 -Component Build)
# -> '1.3.0'
$versionStringIncremented = [string] (Increment-Version 1.2.7 -Component Minor)