首页 > 解决方案 > 查询 PSCustomObject 数组中具有最大值的行

问题描述

我试图找到属性大于另一行属性的行。例子:

$Array
Name         Value
----         ----
test1         105
test2         101
test3         512   <--- Selects this row as it is the largest value

这是我尝试“1 行”,但它不起作用。

$Array | % { If($_.value -gt $Array[0..($Array.Count)].value){write-host "$_.name is the largest row"}}

目前它什么也没输出。

期望的输出:

"test1 is the largest row"

我很难想象如何在没有一些严肃的意大利面条代码的情况下有效地做到这一点。

标签: arrayspowershellsorting

解决方案


您可以利用Sort-Object这样的属性“值”对它们进行排名

$array = @(
    [PSCustomObject]@{Name='test1';Value=105}
    [PSCustomObject]@{Name='test2';Value=101}
    [PSCustomObject]@{Name='test3';Value=512}
)

$array | Sort-Object -Property value -Descending | Select-Object -First 1

输出

Name  Value
----  -----
test3   512

要合并您的写入主机,您只需运行您通过 foreach 选择的主机。

$array | Sort-Object -Property value -Descending |
    Select-Object -First 1 | Foreach-Object {Write-host $_.name,"has the highest value"}

test3 has the highest value

或捕获到变量

$Largest = $array | Sort-Object -Property value -Descending | Select-Object -First 1
Write-host $Largest.name,"has the highest value"

test3 has the highest value

推荐阅读