PowerTip: Find the Largest Number in a PowerShell Array


Summary: Easily find the largest number in a Windows PowerShell array.

Hey, Scripting Guy! Question How can I use Windows PowerShell to easily find the largest number in an array of numbers?

Hey, Scripting Guy! Answer 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 :

Comments (4)

  1. Greg Wojan says:

    @jrv,

    I think the [array] cast is unnecessary. What's happening because of operator precedence is the first item (1) is being cast as it's own array giving you $a which is any object[] containing an array plus seven integers.

    $a = [array](1,2,5,6,3,2,9,1)

    or

    $a = 1,2,5,6,3,2,9,1

    probably gives you what you expect — an array of 8 integers.

  2. jrv says:

    Hmmm…

    This is odd…  Thisi does not work as expected.

    See:

    $a = [array]1,2,5,6,3,2,9,1

    $a|%{$_.GetType()}

    IsPublic IsSerial Name                                     BaseType

    ——– ——– —-                                     ——–

    True     True     Object[]                                 System.Array

    True     True     Int32                                    System.ValueType

    True     True     Int32                                    System.ValueType

    True     True     Int32                                    System.ValueType

    True     True     Int32                                    System.ValueType

    True     True     Int32                                    System.ValueType

    True     True     Int32                                    System.ValueType

    True     True     Int32                                    System.ValueType

  3. jrv says:

    @Greg

    Exactly my point.

    I am not a big fan of use of casts in PowerShell.  They can have some difficult to find side-effects.  We should not use constructs without a complete understanding of how they work in each situation.  Scripting is intended to be sparse.  Support for more fine-detailed code usage is good but only when needed.

  4. Rakhesh says:

    Nice! Much faster than { $a | sort -Descending | select -First 1 } which is what I was doing so far.

    PS> (measure-command { $a | sort -Descending | select -First 1 }).TotalMilliseconds

    3.879

    PS> (measure-command { $a | measure -Maximum }).TotalMilliseconds

    1.3444

Skip to main content