【问题标题】:Get highest count of items from multiple arrays in PowerShell从 PowerShell 中的多个数组中获取最多的项目数
【发布时间】:2021-10-08 08:02:51
【问题描述】:

假设我在 powershell 中有多个非数字数组:

$a = (a, b, c, d)             # $a.count equals 4 items
$b = (e, f, g, h, i, j)       # $b.count equals 6 items, which is the highest count of items in one of the arrays
$c = (k, l, m, n, o)          # $c.count equals 5 items
$d = (p, q)                   # $d.count equals 2 items
...

在声明了所有这些数组之后,我想从所有这些数组中获取最多的计数,在上述情况下,数组 $b 的计数为 6。 有没有一种简单的方法来实现这一点,而不是将每个数组与下一个数组进行比较并检查计数是否比以前高?

提前非常感谢!

【问题讨论】:

  • 您只想获得最高计数吗?或者数组也需要$b

标签: arrays windows powershell logic script


【解决方案1】:

您可以使用Measure-Object Cmdlet with -Property and -Maximum Parameters-Property 参数允许您根据属性值进行测量(在这种情况下,它基于数组 Count 属性)

$a = ('a', 'b', 'c', 'd')
$b = ('e', 'f', 'g', 'h', 'i', 'j')
$measureInfo = ($a, $b) | Measure-Object -Property Count -Maximum
Write-Output $measureInfo.Maximum # This will print 6

请注意,这将仅打印最大 Count。如果您还想要该数组,则可能必须根据此值应用过滤器。

$MaxArray = ($a, $b) | Where-Object {$_.Count -eq $maximumCount.Maximum}

【讨论】:

  • 谢谢,您的解决方案是正确的,正是我想要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-27
  • 2011-04-16
相关资源
最近更新 更多