Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 34 ยท Language Basics

Arrays and Hashtables

Learn PowerShell arrays and hashtables: ranges, indexing, why += is slow, List[T], ordered hashtables, key lookup and a first look at splatting.

Almost every script needs to hold more than one value. A list of server names, the files in a folder, a set of options for a command: PowerShell gives you two built-in collections for this. An array is an ordered list you read by position. A hashtable is a set of key and value pairs you read by name.

Both are easy to create, which is why people reach for them constantly. They also hide a few surprises, such as arrays that cannot grow, hashtables that forget the order you typed, and a single value that quietly stops being an array. This lesson shows the everyday syntax and then those traps, so they do not cost you an afternoon.

The PowerShell shown here is read-only, because the site cannot run a PowerShell host. Each section ends with a JavaScript stand-in that mimics the behavior, and the lesson says which parts are real PowerShell and which are the model.

Creating arrays

The comma operator builds an array, and @( ) wraps any expression so the result is always an array. Both forms produce a System.Object[] that can hold anything.

POWERSHELL
$colors = 'red', 'green', 'blue'
$numbers = @(10, 20, 30)
$empty = @()
$mixed = @(1, 'two', $true, (Get-Date))

$colors.Count          # 3
$colors[0]             # red
$colors[-1]            # blue  (negative numbers count from the end)
$colors[0, 2]          # red, blue  (several indexes at once)
$colors[1..2]          # green, blue (a slice)

Two spellings give the length: .Count and .Length. Prefer .Count, which also works on other collections.

The range operator .. produces consecutive integers, which makes it handy for loops and slices.

POWERSHELL
1..5                   # 1 2 3 4 5
5..1                   # 5 4 3 2 1
$numbers[0..1]         # the first two items
'a'..'e'               # in PowerShell 6 and later, characters work too

You can pin the element type with a type constraint, which turns on conversion and checking for every item you store.

POWERSHELL
[int[]]$ids = 1, 2, 3
$ids[0] = 'seven'      # error: cannot convert 'seven' to Int32

The one-item surprise

When a command returns exactly one object, you get that object, not an array containing it. Count and index then behave unexpectedly on the wrong thing. Wrap the call in @( ) whenever you need a list.

POWERSHELL
$files = Get-ChildItem *.log        # one file: a FileInfo, zero files: $null
$files = @(Get-ChildItem *.log)     # always an array, possibly empty
$files.Count                        # safe

PowerShell is lenient here and gives .Count to ordinary objects (it reports 1), but the safe habit is still @( ).

Arrays are fixed size

A PowerShell array cannot grow or shrink. The += operator does not append in place. It builds a new array one element longer, copies the old items across and points the variable at the new array.

POWERSHELL
$list = @()
foreach ($i in 1..10000) {
    $list += $i        # copies the whole array every time
}

For a few dozen items nobody notices. For tens of thousands, the copying adds up to real time, because adding item number N copies N minus one items. The total work grows with the square of the item count.

Two ways to collect items

Array += Allocates a new array and copies every item each time.
List[T] Grows in place. Add is cheap.

Use += for small, throwaway lists only.

1 / 2

The best fix is often to let PowerShell collect output for you. Anything a foreach or ForEach-Object writes to the output stream lands in an array when you assign it.

POWERSHELL
$squares = foreach ($i in 1..5) { $i * $i }     # 1 4 9 16 25

When you do need to build a list step by step, use a generic list. It is typed, it grows in place, and Add returns nothing, so it does not pollute your output.

POWERSHELL
$names = [System.Collections.Generic.List[string]]::new()
$names.Add('Ada')
$names.Add('Grace')
$names.Remove('Ada')       # returns $true when it removed something
$names.Count               # 1

The older [System.Collections.ArrayList] also grows in place, but Add returns the new index. Inside a function that number joins your output unless you write [void]$al.Add($x) or $null = $al.Add($x). You will meet that problem again in Functions and Parameters.

The next example counts how many element copies each strategy performs. The counts are real arithmetic for the algorithm, not timing guesses: appending item number N to an immutable array copies N minus one items.

JS Why += gets slower: counting copies

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Useful array operations

Arrays carry a handful of members you will use daily, plus operators that work on whole arrays (covered in Operators and Comparison).

POWERSHELL
$n = 3, 1, 4, 1, 5
$n -contains 4                 # True  (collection on the left)
4 -in $n                       # True  (value on the left)
$n | Sort-Object               # 1 1 3 4 5
$n | Select-Object -Unique     # 3 1 4 5
[array]::Reverse($n)           # reverses in place
$n.Where({ $_ -gt 2 })         # 3 4 5   (method syntax, no pipeline)
$n.ForEach({ $_ * 2 })         # 6 2 8 2 10

An array of arrays is a jagged structure, and @(@(1,2), @(3,4)) flattens its outer layer when you are not careful. To keep an inner array intact, use the unary comma: ,@(1,2).

Hashtables

A hashtable maps keys to values. The literal syntax is @{ key = value; key2 = value2 }, with semicolons or new lines between pairs.

POWERSHELL
$user = @{
    Name  = 'Ada'
    Role  = 'Admin'
    Level = 7
}

$user.Name              # Ada          (dot syntax)
$user['Role']           # Admin        (index syntax)
$user.Level += 1        # 8
$user.Email = '[email protected]'   # assigning a new key adds it
$user.Add('Team', 'Core')         # Add throws if the key exists
$user.Remove('Team')
$user.ContainsKey('Name')         # True
$user.Count                       # 4
$user.Keys                        # the key collection
$user.Values                      # the value collection
$user.Missing                     # $null (no error)

Keys are case-insensitive for strings by default, so $user.name and $user.NAME find the same entry. Values can be anything, including other hashtables and arrays, so nesting works as you would expect.

A hashtable is one object, so the pipeline does not unroll it into entries. To walk the pairs, call GetEnumerator().

POWERSHELL
$user.GetEnumerator() | ForEach-Object { "$($_.Key) = $($_.Value)" }
foreach ($key in $user.Keys) { "$key = $($user[$key])" }

Order is not kept

A plain hashtable gives no promise about the order of its keys. If you print one, the entries can appear in an order that differs from the one you typed. When order matters, such as building a CSV header or a readable report, use an ordered dictionary. It is a hashtable that remembers insertion order.

POWERSHELL
$row = [ordered]@{
    Id   = 1
    Name = 'Ada'
    Role = 'Admin'
}
[pscustomobject]$row     # an object whose properties keep that order

The [pscustomobject] cast is the standard way to turn a hashtable into a proper object with properties, which is what Export-Csv and Format-Table want. Note that [pscustomobject]@{ ... } on a plain hashtable keeps the order you typed, because the literal is parsed in order. The [ordered] attribute matters when you build the table piece by piece.

Splatting preview

A hashtable can hold a command's parameters. You pass it with @ instead of $, and PowerShell turns each key into a named parameter. This is called splatting, and it replaces long lines full of backticks.

POWERSHELL
$copyArgs = @{
    Path        = 'C:\data\reports'
    Destination = 'D:\backup'
    Recurse     = $true
    Force       = $true
}
Copy-Item @copyArgs

You can still add extra parameters on the call line, and you can build the table conditionally, which is its real strength: add Verbose = $true only when a flag is set. Functions and Parameters returns to splatting when functions forward their arguments.

A stand-in for hashtables

JavaScript has no case-insensitive map, but you can model the lookup rule with a small wrapper. The class below lowercases keys on the way in and keeps a record of how each key was first typed, like PowerShell's key comparer plus its stored key.

JS A case-insensitive hashtable model

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The map wrapper and the splat model are stand-ins. The real hashtable is a .NET Hashtable, and the real splat is bound by PowerShell's parameter binder.

When a function builds a result row, prefer [pscustomobject]@{ ... } over a bare hashtable. A hashtable in the pipeline is a single item, so Where-Object and Sort-Object cannot work on its keys as properties.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does $items += 'x' do when $items is an ordinary PowerShell array?

    Arrays are fixed size, so += creates a new array each time. That is fine for small lists and slow for large ones, where a List[T] is the better tool.
  2. 2. You call $files = Get-ChildItem *.log and exactly one file matches. What is in $files?

    A single result is not wrapped. Use @(Get-ChildItem *.log) when you need a real array every time.
  3. 3. Which line creates a hashtable whose keys keep the order you typed them in?

    [ordered] creates an ordered dictionary. A plain @{ } hashtable makes no promise about key order.
  4. 4. What happens when you read a key that does not exist, as in $user.Missing?

    Reading a missing key through dot or index syntax gives $null. Only the Add method throws, and it does so when the key already exists.

Summary

  • Build arrays with commas or @( ), and index them with [0], [-1] and slices like [1..2].
  • Wrap a command in @( ) when you need an array even for zero or one result.
  • Arrays have a fixed size. += copies the array every time, so use List[T] or assign a loop's output for big collections.
  • Hashtables map keys to values, use @{ }, ignore key case, and return $null for missing keys.
  • Use [ordered] for a stable key order and [pscustomobject] to turn data into real objects.
  • Splatting with @name passes a hashtable as named parameters.

Next, see how these values drive decisions in Conditionals and Loops.