Home > Software design >  Get highest count of items from multiple arrays in PowerShell
Get highest count of items from multiple arrays in PowerShell

Time:10-08

let's say I have multiple non-numerical arrays in 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
...

After declaring all those arrays, I would like to get the highest number of counts from all of them, which in the case above would be a count of 6 from array $b. Is there an easy way to achieve this, instead of comparing each array against the next one and check if the count is higher than before?

Thanks very much in advance!

CodePudding user response:

You can use Measure-Object Cmdlet with -Property and -Maximum Parameters. The -Property parameter allows you to measure based on the property value(In this case it's based on the array Count property)

$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

Note that this will print only the maximum Count. If you want the array also, you probably have to apply a filter based on this value.

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