Home > Microsoft, Powershell > PowerShell: Comparing Version numbers

PowerShell: Comparing Version numbers

Comparing version numbers can be tricky from time to time, before you know it you end up in auto-casting issues comparing strings to integers etc. The most common format of a version number in Windows is “Major. Minor. Build. Revision” where each individual item is a figure, but because of the separating dots PowerShell will treat each item as a string.

The .Net System.Version assembly offers a CompareTo method which can do the trick, as shown in the figure below.

versions

The CompareTo method will return 1, 0 or -1  depending whether the compare to version  is higher, equal or lower.

Thanks to Shay Levi (see the comment) I now know a better/faster method for comparing version numbers (thaks Shay). PowerShell has its own [vesion] type. This removes the need of loading the assembly and using New-Object. It still allows for using the CompareTo method and direct compare via -ge, -gt, etc.

versions-2

The CompareTo method will distinguish between the 3 possibilities (>, < or =), but direct comparison might be sufficient in a script.

  1. June 25th, 2009 at 09:17 | #1

    You can get the same results without loading the, try this:

    $v1 = [version]“1.1.0.0″
    $v2 = [version]“2.1.0.0″

    PS > $v1

    Major Minor Build Revision
    —– —– —– ——–
    1 1 0 0

    PS > $v2

    Major Minor Build Revision
    —– —– —– ——–
    2 1 0 0

    You can also compare using the -eq operator:

    PS > $v1 -eq $v2
    False

  2. Rainfellow2002
    April 27th, 2011 at 14:08 | #2

    Nice piece of code, thx lads !

  1. No trackbacks yet.