PowerShell: How to Calculate Sum of Values in Array


Often you may want to calculate the sum of values in an array in PowerShell.

You can use the following syntax to do so:

($my_array | Measure-Object -sum).sum

This particular example will return the sum of values in the array named $my_array.

This approach uses the Measure-Object cmdlet, which can be used to calculate 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 Calculate Sum of Values in Array in PowerShell

Suppose that we create the following array in PowerShell named $my_array:

$my_array = @(4, 15, 20, 22, 30, 45, 50, 51)

We can use the following syntax with the Measure-Object cmdlet to calculate the sum of values in the array:

$my_array | Measure-Object -sum

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

Notice that the Measure-Object cmdlet returns both the count and sum of values in the array.

To only display the sum of values, we can use the following syntax instead:

($my_array | Measure-Object -sum).sum

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

PowerShell sum values in array

We can see that the sum of values in the array is 237.

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

Sum of values: 4 + 15 + 20 + 22 + 30 + 45 + 50 + 51 = 237.

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 the Average of an Array
PowerShell: How to Find Minimum and Maximum Values in Array
PowerShell: How to Find Duplicate Values in Array

Leave a Reply