PowerShell: How to Calculate the Average of an Array


Often you may want to calculate the average value of an array in PowerShell.

You can use the following methods to do so:

Method 1: Calculate Average Value of Array

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

This particular example will return the average value in the array named $my_array.

Method 2: Calculate Average Value of Subset of Array

($my_array[0..3] | Measure-Object -Average).Average

This particular example will return the average value of elements in positions 0 through 3 in the array named $my_array.

The following examples show how to use both methods in practice.

Example 1: Calculate Average Value of 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 to calculate the average value of this array:

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

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

PowerShell calculate average of array

From the output we can see that the average value is 29.625.

We can confirm that this is correct by manually calculating the average of the values in this array:

Average: (4 + 15 + 20 + 22 + 30 + 45 + 50 + 51) / 8 = 29.625

This matches the value that we calculated.

Example 2: Calculate Average Value of Subset of 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 to calculate the average value of the elements in positions 0 through 3 of the array:

($my_array[0..3] | Measure-Object -Average).Average

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

PowerShell calculate average of subset of array

From the output we can see that the average value of the first four elements of the array is 15.25.

We can confirm that this is correct by manually calculating the average of the first four elements in this array:

Average: (4 + 15 + 20 + 22) / 4 = 15.25

This matches the value that we calculated.

Related Tutorials

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

PowerShell: How to Compare Two Arrays
PowerShell: How to Get First Item in Array
PowerShell: How to Find Duplicate Values in Array

Leave a Reply