PowerShell: Return Object with Max Value in Property


Often you may want to return the object that has the max value in a specific property in PowerShell.

You can use the following syntax to do so:

$max = ($my_data | Measure-Object -Property Points -maximum).Maximum
$my_data | Where-Object { $_.Points -eq $max}

This particular example will return the object that has the max value in the Points property of the $my_data object.

The following example shows how to use this syntax in practice.

Example: Return Object with Max Value in Property in PowerShell

Suppose that we have a CSV file named player_data.csv that contains information about various basketball players.

We can use the Import-Csv cmdlet to import the contents of this file into an object named $my_data:

$my_data = Import-Csv player_data.csv

The following screenshot shows how to use this syntax in practice:

Now suppose that we would like to return the entire row from this CSV file that contains the max value in the Points column.

We can use the following syntax to do so:

$max = ($my_data | Measure-Object -Property Points -maximum).Maximum
$my_data | Where-Object { $_.Points -eq $max}

The following screenshot shows how to use this syntax in practice:

PowerShell return object with max value in property

Notice that this returns the row from the CSV file that has a value of 24 in the Points column, which represents the max value in the column.

Feel free to change Points to a different property name to instead return the object with the highest value in a different property.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Calculate the Average of an Array
PowerShell: How to Find Minimum and Maximum Values in Array
PowerShell: How to Compare Two Arrays
PowerShell: How to Find Duplicate Values in Array

Leave a Reply