Compare System.Version in Powershell

Use the three argument System.Version constructor to make new instances with the relevant properties:

[Version]::new($scriptversion.Major,$scriptversion.Minor,$scriptversion.Build) -gt [Version]::new($currentVersion.Major,$currentVersion.Minor,$currentVersion.Build)

Or you can go the verbose way with New-Object:

$NormalizedScriptVersion = New-Object -TypeName System.Version -ArgumentList $scriptversion.Major,$scriptversion.Minor,$scriptversion.Build
$NormalizedCurrentVersion = New-Object -TypeName System.Version -ArgumentList $currentVersion.Major,$currentVersion.Minor,$currentVersion.Build

$NormalizedScriptVersion -gt $NormalizedCurrentVersion 

Use whichever you find more maintainable.


The simplest way is to convert Version object to comparable string:

filter Convert-VersionToComparableText { '{0:0000000000}{1:0000000000}{2:0000000000}' -f $_.Major, $_.Minor, $_.Build }
$SomeVersion = [Version]'1.1.1' | Convert-VersionToComparableText
$OtherVersion = [Version]'1.1.1' | Convert-VersionToComparableText
$SomeVersion -ge $OtherVersion
$SomeVersion = [Version]'1.2.1' | Convert-VersionToComparableText
$OtherVersion = [Version]'1.1.1' | Convert-VersionToComparableText
$SomeVersion -ge $OtherVersion
$SomeVersion = [Version]'1.1.1' | Convert-VersionToComparableText
$OtherVersion = [Version]'1.2.1' | Convert-VersionToComparableText
$SomeVersion -ge $OtherVersion

The output:

True
True
False

Tags:

Powershell