Summary: Easily find the largest number in a Windows PowerShell array.
How can I use Windows PowerShell to easily find the largest number in an array of numbers?
Pipe the array to the Measure-Object cmdlet, and use the –Maximum switch:
PS C:\> $a = [array]1,2,5,6,3,2,9,1
PS C:\> $a | measure -Maximum
Count : 8
Average :
Sum :
Maximum : 9
Minimum :
Property :
what if someday i come across an array that has multiple columns, and only one of the columns has the number i want the maximum of, and i want to return the whole row that contains the highest number?
Hallo John.
1) To get the highest of all numbers in your multidimentional array, you could do:
($a -split ‘ ‘ | measure -Maximum).Maximum
2) If it finds f.x 61 as the biggest nummer, your get your row in your array which contains 61 with:
$a | ? {$_.Contains(61)}
Put all together, it looks like:
$a | ? {$_.Contains([int](($a -split ‘ ‘ | measure -Maximum).Maximum))}
You need to cast your maximum number to fx. integer (=[int])
Hope it makes sense.
PS! I’ve testet with
$a = @(
(1,2,5,6,3,2,9,1),
(12,22,5,61,32,21,9,13)
)
One of those moments where i’m writing if this is greater than that, is greater than that is greater than that, oh maybe i should sort and [-1] it or a switch or…. then it dawned on me there has to be a way to find a maximum value, with a one liner… thanks!