Finding the minimum and maximum values

Finding the minimum and maximum values in a set of numbers is ridiculously easy with PowerShell.

I’ve created a function in line with the other techniques I’ve shown but in reality could be be done equally well as a single line of code:

function get-minmax {
   param (
   $mm = $iarray | Measure-Object -Minimum -Maximum
   New-Object -TypeName PSobject -Property @{
     Minimum = $mm.Minimum
     Maximum = $mm.Maximum

Just pipe the array into Measure-Object and use the –Minimum and –Maximum parameters as shown.  I created an output object for easier handling if you want to do anything else to the array.

You can also get the sum and average of the array with Measure-Object. PowerShell v6.1 adds the Standard Deviation and an –Allstats parameter so you don’t need to specify each individual option:

PS>  $iarray = 1,2,3,4,23,5,6,7,8,9,10,23,11,12,13,7,14,15,16,17,18,20,21,22,11,23,24,25
PS>  $iarray | Measure-Object -AllStats

Count             : 28
Average           : 13.2142857142857
Sum               : 370
Maximum           : 25
Minimum           : 1
StandardDeviation : 7.46030057411125
Property          :

This entry was posted in Powershell, PowerShell v5, PowerShell v6. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s