0
0
PowershellHow-ToBeginner · 2 min read

PowerShell Script to Find Average of Array

Use $average = ($array | Measure-Object -Average).Average to find the average of an array in PowerShell.
📋

Examples

Input[1, 2, 3, 4, 5]
Output3
Input[10, 20, 30]
Output20
Input[]
Output0
🧠

How to Think About It

To find the average, sum all numbers in the array and then divide by how many numbers there are. PowerShell's Measure-Object cmdlet can do this easily by calculating the average directly.
📐

Algorithm

1
Get the array of numbers.
2
Use a built-in command to calculate the average of the array.
3
Store the result in a variable.
4
Print or return the average.
💻

Code

powershell
$array = @(1, 2, 3, 4, 5)
$average = ($array | Measure-Object -Average).Average
if ($null -eq $average) { $average = 0 }
Write-Output "Average is $average"
Output
Average is 3
🔍

Dry Run

Let's trace the array [1, 2, 3, 4, 5] through the code

1

Define array

$array = @(1, 2, 3, 4, 5)

2

Calculate average

$average = (1+2+3+4+5)/5 = 15/5 = 3

3

Output result

Print 'Average is 3'

IterationValueRunning Sum
111
223
336
4410
5515
💡

Why This Works

Step 1: Using Measure-Object

The Measure-Object -Average cmdlet calculates the average of numbers piped into it.

Step 2: Handling empty arrays

If the array is empty, Measure-Object returns $null, so we set average to 0 to avoid errors.

Step 3: Output the result

We use Write-Output to display the average in a readable format.

🔄

Alternative Approaches

Manual sum and count
powershell
$array = @(1, 2, 3, 4, 5)
$sum = 0
foreach ($num in $array) { $sum += $num }
$count = $array.Count
$average = if ($count -gt 0) { $sum / $count } else { 0 }
Write-Output "Average is $average"
This method manually sums and counts elements; it's more verbose but shows the calculation steps explicitly.
Using LINQ-like method with .NET
powershell
$array = @(1, 2, 3, 4, 5)
$average = [System.Linq.Enumerable]::Average($array)
Write-Output "Average is $average"
Uses .NET's LINQ Average method; requires the array to be compatible and may be less familiar to beginners.

Complexity: O(n) time, O(1) space

Time Complexity

Calculating the average requires visiting each element once to sum values, so it is O(n) where n is the number of elements.

Space Complexity

The calculation uses a fixed amount of extra space regardless of input size, so it is O(1).

Which Approach is Fastest?

Using Measure-Object is efficient and concise; manual summing is similar in speed but more verbose; .NET LINQ may add overhead.

ApproachTimeSpaceBest For
Measure-Object -AverageO(n)O(1)Quick and simple scripts
Manual sum and countO(n)O(1)Learning and explicit control
.NET LINQ AverageO(n)O(1)When using .NET methods or complex queries
💡
Use Measure-Object -Average for a quick and simple average calculation in PowerShell.
⚠️
Beginners often forget to handle empty arrays, which can cause errors when calculating the average.