Home > Software engineering >  Compare two numbers representing the version of a Software with several point
Compare two numbers representing the version of a Software with several point

Time:12-16

I want to compare create a function that compare/verifies that a version number is smaller than the another one. The numbers are :

$version1 = 23.0.46.0
$version2 = 24.1.154.0

When I use a simple if condition like below, it does not work because it gives me False

IF(23.0.46.0 -lt 24.1.154.0){
    Write-Host "True"
}
Else
{
    Write-Host "False"
}

I have the idea to split the version number by the points into an array. Then do a loop to compare the parts of each versions until that one is smaller than the another one. In this case it would be directly in the first iteration because 23<24. However I am newly in Powersehll

Thank you for your help

CodePudding user response:

You can use the version class for this. This simple function will return the higher version between 2 inputs:

function Compare-Version {
    param(
        [version]$a,
        [version]$b
    )

    ($a, $b)[$a -lt $b]
}

Compare-Version '25.0.46.0' '25.1.154.0'

Major  Minor  Build  Revision
-----  -----  -----  --------
25     1      154    0

Note that, for the input to be valid, it must comply with the version syntax.

From Remarks of the official documentation:

Version numbers consist of two to four components: major, minor, build, and revision. The major and minor components are required; the build and revision components are optional, but the build component is required if the revision component is defined. All defined components must be integers greater than or equal to 0. The format of the version number is as follows (optional components are shown in square brackets ([ and ]):

major.minor[.build[.revision]]

  • Related