PowerShell中表中的自然排序版本号

时间:2018-02-14 22:58:14

标签: powershell sorting

我编写了一个PowerShell函数来查询Citrix Receiver版本:https://gist.github.com/aaronparker/8204e49405a78245301dae1ebaf1df71

这将返回一个如下所示的数组/表:

Platform                                         Version
--------                                         -------
Receiver for Linux                               13.0
Receiver for Linux                               13.1
Receiver for Linux                               13.2
Receiver for Linux                               13.2.1
Receiver for Linux                               13.3
Receiver for Linux                               13.4
Receiver for Linux                               13.5
Receiver for Linux                               13.6
Receiver for Linux                               13.7
Receiver for Linux                               13.8
Receiver for Mac                                 11.9.15
Receiver for Mac                                 12.1.100
Receiver for Mac                                 12.2
Receiver for Mac                                 12.3
Receiver for Mac                                 12.4
Receiver for Mac                                 12.5
Receiver for Mac                                 12.6
Receiver for Mac                                 12.7
Receiver for Mac                                 12.8.1
Receiver for Windows                             4.10.1
Receiver for Windows                             4.3.100
Receiver for Windows                             4.5
Receiver for Windows                             4.6
Receiver for Windows                             4.7
Receiver for Windows                             4.8

我想在Version属性上执行自然搜索。如果只对Versions属性进行排序(或者对仅包含版本号的数组进行排序),我可以成功地做到这一点,例如:

$SortNatural = { [regex]::Replace($_, '\d+', { $args[0].Value.PadLeft(20) }) }
$array.Version | Sort-Object $SortNatural

但是,在对整个表进行排序时,这会变得更加困难。我想在平台和版本上排序。当然,我可以这样做:

$array | Sort-Object -Property Platform, @{Expression = '$_.Version'; Ascending = $True}

但这并没有提供正确的排序。我正在尝试使用带有排序对象的表达式来理解如何使用自然排序。

有关实现我想要的排序方法的任何指示或替代建议吗?

1 个答案:

答案 0 :(得分:0)

对于任何想要做同样事情的人来说,感谢@Bill_Stewart,这是如何修复的。上面Gist链接中的完整代码。

$Receivers += $ReceiverLinks | Select-Object @{Name = "Platform"; Expression = {$_.innerText -replace $RegExVersion}}, `
                @{Name = "Version"; Expression = {[Version]$($_.innerText -replace $RegExNumbers)}}
$Receivers | Sort-Object -Property Platform, @{Expression = 'Version'; Descending = $True}