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

Ste*_*e B 2 sorting powershell

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

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

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

在 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
Run Code Online (Sandbox Code Playgroud)

输出是

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    
Run Code Online (Sandbox Code Playgroud)

但是,我希望SomeText被命令上升......

小智 5

将排序顺序与哈希表一起应用似乎会破坏属性顺序,
因此您需要一个选择对象来重新建立正确的顺序

$data | Sort-Object -Property @{e="SomeInt";Descending=$True},
                              @{e="SomeText";Descending=$False}|
    Select-Object SomeInt,SomeText
Run Code Online (Sandbox Code Playgroud)

示例输出:

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
Run Code Online (Sandbox Code Playgroud)

编辑:这不是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
Run Code Online (Sandbox Code Playgroud)