将代表软件版本的两个数字与几个点进行比较

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

我想比较创建一个 compare/verifies 版本号小于另一个版本号的函数。数字是:

$version1 = 23.0.46.0
$version2 = 24.1.154.0

当我使用如下简单的 if 条件时,它不起作用,因为它给出了 False

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

我有想法将版本号按点拆分成一个数组。然后做一个循环来比较每个版本的部分,直到那个比另一个小。在这种情况下,它将直接在第一次迭代中,因为 23<24。但是我是新加入 Powersehll

感谢您的帮助

您可以为此使用 version class。这个简单的 function 将 return 2 个输入之间的更高版本:

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

请注意,要使输入有效,它必须符合版本语法。

来自官方文档的备注

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]]