PowerTip: Find the Largest Number in a PowerShell Array

PowerTip: Find the Largest Number in a PowerShell Array

  • Comments 4
  • Likes

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 :

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • 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

  • @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.

  • @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.

  • 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