0
0
PowershellHow-ToBeginner · 2 min read

PowerShell Script to Count Elements in Array

Use $array.Length to count the number of elements in a PowerShell array, for example: $count = $array.Length.
📋

Examples

Input[1, 2, 3]
Output3
Input['apple', 'banana', 'cherry', 'date']
Output4
Input[]
Output0
🧠

How to Think About It

To count elements in an array, simply find the property that stores the number of items. In PowerShell, arrays have a Length property that tells you how many elements they contain. You just access this property to get the count.
📐

Algorithm

1
Create or get the array you want to count.
2
Access the <code>Length</code> property of the array.
3
Store or output the value of <code>Length</code> as the count of elements.
💻

Code

powershell
$array = @("apple", "banana", "cherry")
$count = $array.Length
Write-Output "Number of elements: $count"
Output
Number of elements: 3
🔍

Dry Run

Let's trace counting elements in the array @("apple", "banana", "cherry") through the code

1

Define the array

$array = @("apple", "banana", "cherry")

2

Get the length

$count = $array.Length # $count is 3

3

Output the count

Write-Output "Number of elements: 3"

StepArray ContentCount
1["apple", "banana", "cherry"]
2["apple", "banana", "cherry"]3
3["apple", "banana", "cherry"]3
💡

Why This Works

Step 1: Arrays have a Length property

PowerShell arrays store their size in the Length property, which counts all elements.

Step 2: Accessing Length gives the count

By accessing $array.Length, you get the total number of elements without looping.

Step 3: Output shows the count

Using Write-Output prints the count so you can see the result.

🔄

Alternative Approaches

Using Measure-Object
powershell
$array = @(1, 2, 3)
$count = ($array | Measure-Object).Count
Write-Output "Number of elements: $count"
This method works but is slower because it pipes the array through a command.
Using .Count property
powershell
$array = @("a", "b", "c")
$count = $array.Count
Write-Output "Number of elements: $count"
The .Count property also works for arrays and collections, similar to .Length.

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

Time Complexity

Accessing the Length property is a constant time operation because the array size is stored internally.

Space Complexity

No extra memory is needed beyond the array itself; the count is retrieved without additional storage.

Which Approach is Fastest?

Using $array.Length or $array.Count is fastest; piping to Measure-Object is slower due to processing overhead.

ApproachTimeSpaceBest For
$array.LengthO(1)O(1)Fastest, simplest for arrays
$array.CountO(1)O(1)Works for arrays and collections
Measure-ObjectO(n)O(1)When working with pipeline objects
💡
Use $array.Length for a quick and efficient count of array elements.
⚠️
Beginners sometimes try to count elements by looping instead of using the built-in Length property.