在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
升序...
答案 0 :(得分:2)
对哈希表应用排序顺序似乎会破坏属性顺序,
因此您需要一个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