Arrays
Prerequisites: Variables, Operators
An array holds an ordered list of values.
$fruits = 'apple', 'banana', 'cherry'
$fruits[0]
$fruits[-1]
$fruits.Count
$fruits[0..1] -join ', '
$empty = @()
$empty.Count
apple
cherry
3
apple, banana
0
- A comma-separated list creates an array;
@()creates an empty one (or forces a result to be an array). - Indexes start at 0; negative indexes count from the end.
0..1is a range, so$fruits[0..1]takes a slice.
Adding and removing
$fruits = @('apple', 'banana')
$fruits += 'cherry'
$fruits = $fruits | Where-Object { $_ -ne 'banana' }
$fruits -join ', '
apple, cherry
Arrays have a fixed size: += actually creates a new, bigger array
each time. That's fine for small lists, but slow in a loop with thousands
of items. Use a list instead:
$list = [System.Collections.Generic.List[string]]::new()
$list.Add('apple')
$list.Add('banana')
$list.Remove('apple') | Out-Null
$list.Count
$list[0]
1
banana
The easiest way to build an array
Assign a loop's output directly — PowerShell collects it into an array:
$squares = foreach ($n in 1..5) { $n * $n }
$squares -join ' '
1 4 9 16 25
One item or many?
A command that returns a single object returns that object, not an array
— so .Count and indexing can surprise you. Wrap the call in @( ) to
always get an array: $files = @(Get-ChildItem *.log).
Practice
Create an array of five numbers, then print the largest and the total.
Show solution
$numbers = 12, 7, 31, 5, 18
($numbers | Measure-Object -Maximum).Maximum
($numbers | Measure-Object -Sum).Sum
31
73