TExcelTAD
Home › PowerShell › PowerShell Arrays

PowerShell Arrays

An array is an ordered collection of values. PowerShell creates one whenever you separate values with commas, and many commands return arrays, so you work with them constantly.

Creating arrays

powershell · try it yourself
$colors = 'red', 'green', 'blue'          # comma list
$numbers = 1..5                           # range
$empty = @()                              # empty array
$single = @('only one')                   # array with one element
$mixed = @(42, 'text', $true, 3.5)        # any types

$colors.Count
$numbers -join ','
$empty.Count
$single.Count
$mixed[2]
3
1,2,3,4,5
0
1
True

The array subexpression @( … ) always produces an array, even with zero or one element. Use it around commands whose output you want to count: @(Get-ChildItem *.log).Count.

Accessing elements

Indexes start at 0. Negative indexes count from the end, and you can pass a range or a list of indexes to get several elements at once:

powershell · try it yourself
$planets = 'Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter'
$planets[0]
$planets[-1]
$planets[1..3] -join ', '
$planets[0, 2, 4] -join ', '
$planets[-2..-1] -join ', '
"[$($planets[10])]"
Mercury
Jupiter
Venus, Earth, Mars
Mercury, Earth, Jupiter
Mars, Jupiter
[]

Reading past the end returns $null (no error unless strict mode is on). Assigning past the end, however, is an error: arrays have a fixed size.

Changing arrays

You can change an existing element by index. "Adding" with += actually creates a new array that is one element longer and copies everything over:

powershell · try it yourself
$queue = @('build', 'test')
$queue[1] = 'unit-test'
$queue += 'deploy'
$queue -join ' -> '

$queue = $queue | Where-Object { $_ -ne 'unit-test' }   # "remove" by filtering
$queue -join ' -> '
build -> unit-test -> deploy
build -> deploy

That copying is fine for a few dozen items but slow for thousands. For big collections use a List, which grows in place:

powershell · try it yourself
$list = [System.Collections.Generic.List[string]]::new()
$list.Add('alpha')
$list.Add('beta')
$list.AddRange([string[]]@('gamma', 'delta'))
$list.Remove('beta') | Out-Null
$list.Insert(0, 'zero')
$list.Count
$list -join ', '
$list.Contains('gamma')
4
zero, alpha, gamma, delta
True

A even simpler pattern is to let PowerShell collect loop output for you: $squares = foreach ($n in 1..1000) { $n * $n } builds the array in one go, with no += at all.

Useful operations

powershell · try it yourself
$scores = 72, 95, 88, 61, 95
($scores | Sort-Object) -join ' '
($scores | Sort-Object -Descending -Unique) -join ' '
($scores | Measure-Object -Sum -Average -Maximum).Average
$scores -contains 61
[array]::IndexOf($scores, 88)
$scores.Where({ $_ -ge 90 }).Count
$scores.ForEach({ $_ + 5 }) -join ' '
61 72 88 95 95
95 88 72 61
82.2
True
2
2
77 100 93 66 100

.Where() and .ForEach() are array methods that work like Where-Object and ForEach-Object but run on an array that is already in memory, often faster.

Typed and multi-dimensional arrays

Add a type to restrict what an array may hold; values are converted on the way in:

powershell · try it yourself
[int[]]$ports = '80', '443', 8080
$ports[0].GetType().Name
$ports.Count

$grid = @(
    @(1, 2, 3),
    @(4, 5, 6)
)
$grid[1][2]
$grid.Count
$grid[0].Count
Int32
3
6
2
3

A "jagged" array of arrays like $grid is the usual way to store a table of values. For rows with named columns, use an array of objects (PSCustomObject lesson) instead.

Note: When a function returns an array with one element, PowerShell "unrolls" it into the single value. Wrap the call in @( ) if you need an array no matter what.

Test yourself

What does $a = 'x','y','z'; $a[-1] return?

  1. x
  2. y
  3. z
  4. An error

Why is $array += $item slow inside a big loop?

  1. It sorts the array each time
  2. It creates a new copy of the array every time
  3. It converts all values to strings
  4. It isn't slow

How do you make sure $r is always an array, even if Get-Thing returns one object?

  1. $r = Get-Thing
  2. $r = @(Get-Thing)
  3. $r = [Get-Thing]
  4. $r = $(Get-Thing)