0
0
PowershellHow-ToBeginner · 2 min read

PowerShell Script to Find Sum of Array

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

Examples

Input[1, 2, 3]
Output6
Input[10, 20, 30, 40]
Output100
Input[]
Output0
🧠

How to Think About It

To find the sum of numbers in an array, think of adding each number one by one. PowerShell provides a simple way to do this using the Measure-Object cmdlet with the -Sum option, which adds all elements automatically.
📐

Algorithm

1
Get the array of numbers.
2
Use a built-in command to calculate the sum of all elements.
3
Store the result in a variable.
4
Output the sum.
💻

Code

powershell
$array = @(1, 2, 3, 4, 5)
$sum = ($array | Measure-Object -Sum).Sum
Write-Output "Sum of array elements is: $sum"
Output
Sum of array elements is: 15
🔍

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 sum

$sum = (1 + 2 + 3 + 4 + 5) = 15

3

Output result

Print 'Sum of array elements is: 15'

Array ElementRunning Total
11
23
36
410
515
💡

Why This Works

Step 1: Using Measure-Object

The Measure-Object cmdlet can calculate statistics like sum, count, and average on collections.

Step 2: Piping the array

We send the array elements through the pipeline to Measure-Object to process them.

Step 3: Extracting the sum

The -Sum option tells it to add all numbers, and we access the .Sum property to get the total.

🔄

Alternative Approaches

Using a foreach loop
powershell
$array = @(1, 2, 3, 4, 5)
$sum = 0
foreach ($num in $array) {
    $sum += $num
}
Write-Output "Sum of array elements is: $sum"
This method is more manual but helps beginners understand the addition process step-by-step.
Using the .NET Sum() method
powershell
$array = @(1, 2, 3, 4, 5)
$sum = [System.Linq.Enumerable]::Sum($array)
Write-Output "Sum of array elements is: $sum"
This uses .NET's LINQ Sum method, which is concise but requires understanding of .NET classes.

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

Time Complexity

The sum operation must look at each element once, so it takes linear time proportional to the array size.

Space Complexity

No extra space is needed besides a variable to hold the sum, so space is constant.

Which Approach is Fastest?

Using Measure-Object or the .NET Sum method are both efficient and concise; the foreach loop is clear but slightly longer.

ApproachTimeSpaceBest For
Measure-Object -SumO(n)O(1)Quick and readable for beginners
foreach loopO(n)O(1)Learning and understanding addition process
.NET Sum() methodO(n)O(1)Concise code with .NET knowledge
💡
Use Measure-Object -Sum for a quick and readable sum of array elements.
⚠️
Beginners often try to add arrays directly without looping or using Measure-Object, which causes errors.