PowerShell: How to Sum Values in Specific Column


Often you may want to calculate the sum of values in a specific column of an object in PowerShell.

You can use the following syntax to do so:

($data | Measure-Object 'points' -sum).sum

This particular example calculates the sum of values in the ‘points’ column of the object named $data.

This approach uses the Measure-Object cmdlet, which calculates numeric values of an array.

By default, the Measure-Object cmdlet only calculates the count of elements in an array, but by using the -sum option along with .sum we are able to calculate the sum of values and then only display the sum in the output.

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

Example: How to Sum Values in Specific Column of Object in PowerShell

Suppose that we use the Import-Csv cmdlet to import a CSV file named nba_data.csv and then save the values from the file in an object named $data:

$data = Import-Csv nba_data.csv

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

The $data object contains four columns with information about various basketball players.

Suppose that we would like to sum only the values from the points column.

We can use the following syntax to do so:

($data | Measure-Object 'points' -sum).sum

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

PowerShell sum values in column

We can see that the sum of values in the points column is 220.

We can verify that this is correct by manually calculating the sum of values in the column:

Sum of values: 15 + 22 + 35 + 20 + 15 + 45 + 22 + 14 + 23 + 9 = 220.

This matches the value that we calculated.

Note: You can find the complete documentation for the Measure-Object cmdlet in PowerShell here.

Related Tutorials

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

PowerShell: How to Calculate Sum of Values in Array
PowerShell: How to Calculate the Average of an Array
PowerShell: How to Find Minimum and Maximum Values in Array

Leave a Reply