用两个数字对数组中的版本号进行排序不正确

时间:2019-04-04 14:53:30

标签: arrays powershell sorting

我正在尝试按降序对版本号进行排序,尽管“ 10”大于2,但“ W2018.1.10”等版本却低于“ W2018.1.2”。

$request = 'place from where I pull the version list'
$content = Invoke-RestMethod -Uri $request -Method GET

$versionarray = $content.versionlist[0].Versionen -split ", "
$sortedArray = $versionArray + "W2018.2.10.1" | sort -Descending
Write-Output $sortedArray

当前数组如下:

W2019.2.8.7
W2019.2.8.6
W2019.2.8.5
W2019.2.8.3
W2018.2.10.1

应该看起来像这样:

W2018.2.10.1
W2019.2.8.7
W2019.2.8.6
W2019.2.8.5
W2019.2.8.3

2 个答案:

答案 0 :(得分:0)

非常脏:)

    $x2 = @("W2019.2.8.7","W2019.2.9.7","W2018.2.1.7","W2020.1.1.7")

$hash = @{}

foreach ($x in $x2)

{

    $x -match "(w\d*\.)(\d*.\d*.\d*)"

$property = [ordered]@{

    'fullname' =  $matches[0]
    'sort' = $matches[2]
    }
    $res = New-Object -TypeName psobject -Property $property

$hash.add($res.fullname,$res.sort)
}

$res2 = ($hash |Sort-Object -Property value).Keys

$res2

答案 1 :(得分:0)

说明几种方法:

## Q:\Test\2019\04\04\SO_55519038.ps1
## $ToNatural from Roman Kuzmin source <https://stackoverflow.com/a/5429048/6811411>
$ToNatural = { [regex]::Replace($_, '\d+', { $args[0].Value.PadLeft(20,"0") }) }

$versionarray = ("W2018.2.1.7",
                 "W2019.2.8.7",
                 "W2019.2.9.7",
                 "W2019.2.10.7",
                 "W2019.2.1.7")

"`nCasting all digits to version type"
$versionarray | ForEach-Object { [version]($_ -replace '^W')} | Sort

"`nSorting with `$ToNatural`n"
$versionarray | Sort $ToNatural

"`nBuilding a [PSCustomObject] with last 3 dot seperated numbers cast to version"
$versionarray | ForEach-Object {
    [PSCustomObject]@{
        VersionString = $_
        Version       = [version]($_ -split '\.',2)[1]
    }
} | Sort Version,VersionString | ft

示例输出:

> Q:\Test\2019\04\04\SO_55519038.ps1

Casting all digits to version type

Major  Minor  Build  Revision
-----  -----  -----  --------
2018   2      1      7
2019   2      1      7
2019   2      8      7
2019   2      9      7
2019   2      10     7

Sorting with $ToNatural

W2018.2.1.7
W2019.2.1.7
W2019.2.8.7
W2019.2.9.7
W2019.2.10.7

Building a [PSCustomObject] with last 3 dot seperated numbers cast to version

VersionString Version
------------- -------
W2018.2.1.7   2.1.7
W2019.2.1.7   2.1.7
W2019.2.8.7   2.8.7
W2019.2.9.7   2.9.7
W2019.2.10.7  2.10.7