gpt4 book ai didi

powershell - 使用一个字段降序然后升至第二个字段对数据进行排序?

转载 作者:行者123 更新时间:2023-12-02 23:36:35 25 4
gpt4 key购买 nike

在PowerShell脚本中,我想按一个字段降序然后将另一个字段升序对自定义对象数组进行排序。

但是,排序对象函数仅允许一种排序规范(据我所知)。

如何使用复杂的排序进行排序?

在SQL中,我将使用Order by Date ASC, SomeField DESC。在PowerShell中有等效的功能吗?

为了说明这一点,下面是一个小示例:

$data = @(
New-Object PSObject -Property @{ SomeInt = 2 ; SomeText = "a" }
New-Object PSObject -Property @{ SomeInt = 2 ; SomeText = "b" }
New-Object PSObject -Property @{ SomeInt = 2 ; SomeText = "c" }
New-Object PSObject -Property @{ SomeInt = 3 ; SomeText = "d" }
New-Object PSObject -Property @{ SomeInt = 3 ; SomeText = "e" }
New-Object PSObject -Property @{ SomeInt = 3 ; SomeText = "f" }
New-Object PSObject -Property @{ SomeInt = 1 ; SomeText = "g" }
New-Object PSObject -Property @{ SomeInt = 1 ; SomeText = "h" }
New-Object PSObject -Property @{ SomeInt = 1 ; SomeText = "i" }
New-Object PSObject -Property @{ SomeInt = 0 ; SomeText = "j" }
New-Object PSObject -Property @{ SomeInt = 0 ; SomeText = "k" }
New-Object PSObject -Property @{ SomeInt = 0 ; SomeText = "l" }
New-Object PSObject -Property @{ SomeInt = 0 ; SomeText = "m" }
New-Object PSObject -Property @{ SomeInt = 0 ; SomeText = "n" }
)

$data | Sort -Descending SomeInt, SomeText | Select SomeInt, SomeText

输出是
SomeInt SomeText
------- --------
3 f
3 e
3 d
2 c
2 b
2 a
1 i
1 h
1 g
0 n
0 m
0 l
0 k
0 j

但是,我希望 SomeText升序排列...

最佳答案

将排序顺序与哈希表一起使用似乎会破坏属性顺序,
所以您需要一个Select-Object来重新建立正确的顺序

$data | Sort-Object -Property @{e="SomeInt";Descending=$True},
@{e="SomeText";Descending=$False}|
Select-Object SomeInt,SomeText

样本输出:
SomeInt SomeText
------- --------
3 d
3 e
3 f
2 a
2 b
2 c
1 g
1 h
1 i
0 j
0 k
0 l
0 m
0 n

编辑:不是Sort-Object,它不遵守给定的顺序,而是New-Object
> New-Object PSObject -Property @{ SomeInt = 2 ; SomeText = "a" }

SomeText SomeInt
-------- -------
a 2

> New-Object PSObject -Property @{ SomeText = "a" ; SomeInt = 2 }

SomeText SomeInt
-------- -------
a 2

关于powershell - 使用一个字段降序然后升至第二个字段对数据进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53617765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com