PowerShell Genie

PowerShell Hashtables

A hashtable maps keys to values, written @{ Key = 'Value' }. Look a value up by key with $hash['Name'] or the shorter $hash.Name. Lookup does not depend on order or position.

Lesson 2 min read Windows PowerShell 5.1 and PowerShell 7

Documentation: Microsoft Learn

Overview

Hashtables turn up in three places you cannot avoid. They are how you pass a bundle of parameters to a command, which is called splatting. They are how you define calculated properties for Select-Object and Sort-Object, using the Name and Expression keys. And they are how you build objects, by casting a hashtable to [pscustomobject].

Keys are case-insensitive by default, so $h.Name and $h.NAME reach the same entry. The order of keys is not preserved: enumerate a hashtable twice and the keys can come back in a different sequence. When order matters, write [ordered]@{ } instead, which is exactly the same syntax with a guarantee attached.

Adding a key is assignment to a key that does not exist yet. Removing one uses the Remove method.

Inspect this example’s structure

Read the command and its supplied arguments. This example requires real PowerShell or its module; this diagram does not execute it.

$student = @{ Name = 'Ada';Course = 'PowerShell' } $student['Name']
  1. Stage 1$studentPositional values or no named parameters

    What happens

    The first line builds a hashtable with two keys. The second reads one of them using dot notation, which returns PowerShell. Bracket notation, $student['Course'], does the same thing and is what you need when a key name contains a space or is held in a variable.

    Worth remembering

    • @{ Key = 'Value' } creates it. Read with .Key or ['Key'].
    • Keys are case-insensitive.
    • Key order is not guaranteed. Use [ordered]@{ } when it matters.
    • Hashtables drive splatting, calculated properties and [pscustomobject].

    Primary documentation

    PowerShell objects and pipelines documentation

    Try it

    Illustrative output · values vary by environment

    1PS> $student = @{ Name = 'Ada';Course = 'PowerShell' }
    2PS> $student['Name']

    Example reader

    Inspect this page's example

    Fictional browser data when supported

    Run supported commands against the practice data, or inspect the example without executing it.

    Ready to inspect.

      Builds a two-key hashtable and reads one value by key.

      Show reference output

      Illustrative output · values vary by environment

      Ada

      Keep going

      Next: PowerShell PSCustomObject
      Genie guidePowerShell Hashtables

      A hashtable maps keys to values, written @{ Key = 'Value' }. Look a value up by key with $hash['Name'] or the shorter $hash.Name. Lookup does not depend on order or position.