This is a reusable function to enable quick comparisons between two strings representing version control numbers. I’ve adapted this from JavaScript with the pleasure of being able call the PowerShell [version] object constructor. Windows do make certain activities easier.
# Shorter version
function isHigherVersion ($a,$b){
# This assumes the query as version $a is greater than $b by reconstructing PowerShell version object
$regexVersion='^(\d+)\.{1}(\d+)\.{0,1}(\d+){0,1}\.{0,1}(\d+){0,1}'
[void]($a -match $regexVersion)
1..4|%{new-variable "a$_" -value $matches[$_] -force}
[void]($b -match $regexVersion)
1..4|%{new-variable "b$_" -value $matches[$_] -force}
return [Version]::new($a1,$a2,$a3,$a4) -gt [Version]::new($b1,$b2,$b3,$b4)
}
# Overly verbose version
function compareVersions ($a,$b){
# This assumes the query as version $a is greater than $b by reconstructing PowerShell version object
$majorRegex = '^(\d+)\.'
$minorRegex = '^\d+\.(\d+)'
$buildRegex = '^\d+\.\d+\.(\d+)'
$revisionRegex = '^\d+\.\d+\.\d+\.(\d+)'
$aMajor= .{[void]($a -match $majorRegex);return $matches[1]}
$aMinor= .{[void]($a -match $minorRegex);return $matches[1]}
$aBuild= .{[void]($a -match $buildRegex);return $matches[1]}
$aRevision=.{[void]($a -match $revisionRegex);return $matches[1]}
$bMajor= .{[void]($b -match $majorRegex);return $matches[1]}
$bMinor= .{[void]($b -match $minorRegex);return $matches[1]}
$bBuild= .{[void]($b -match $buildRegex);return $matches[1]}
$bRevision=.{[void]($b -match $revisionRegex);return $matches[1]}
return [Version]::new($aMajor,$aMinor,$aBuild,$aRevision) -gt [Version]::new($bMajor,$bMinor,$bBuild,$bRevision)
}
PS C:\Windows\system32> compareVersions 1.1.1.1 1.1.0.2
True
Categories: