Tomek
Tomek

Reputation: 671

Compare System.Version in Powershell

I have a case where I have to make a decision in script based on comparing versions Consider this example:

PS C:\>
[version]$SomeVersion='1.1.1'
[version]$OtherVersion='1.1.1.0'

PS C:\> $SomeVersion

Major  Minor  Build  Revision
-----  -----  -----  --------
1      1      1      -1      

PS C:\> $OtherVersion

Major  Minor  Build  Revision
-----  -----  -----  --------
1      1      1      0       

PS C:\>$SomeVersion -ge $OtherVersion
False

I would like to omit revision when comparing objects of type System.Version
I Can't find any sane way of doing that.
Is there any?

Note - I've tried doing :

PS C:\> ($scriptversion |select major,minor,build) -gt ($currentVersion|select major,minor,build)

Cannot compare "@{Major=1; Minor=1; Build=1}" to "@{Major=1; Minor=1; 
Build=1}" because the objects are not the same type or the object "@{Major=1; 
Minor=1; Build=1}" does not implement "IComparable".
At line:1 char:1
+ ($scriptversion |select major,minor,build) -gt ($currentVersion |sele ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [], ExtendedTypeSystemException
+ FullyQualifiedErrorId : PSObjectCompareTo

when I try to override revision number with 0 it says that it's read-only property... I have a workaround But I hoped to do it better with system.version

Upvotes: 11

Views: 30059

Answers (2)

Bacon Bits
Bacon Bits

Reputation: 32230

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.

Upvotes: 16

fdafadf
fdafadf

Reputation: 819

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

Upvotes: 2

Related Questions