On this page

PowerShell Hash Tables

Published on June 9, 2026

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

A PowerShell hash table is a key-value data structure that lets you store, retrieve, and manipulate named data without numeric indexes. Unlike arrays — where each element is accessed by its position — a hash table uses a unique key to identify each value. Hash tables are fundamental to clean PowerShell scripting: they power splatting, drive lookup tables, define custom object properties, and appear throughout pipeline operations. This lesson covers every aspect of hash tables, from basic syntax to advanced patterns used in production scripts.


How Hash Tables Work​

A hash table stores each value alongside a key. Internally, PowerShell uses a hashing algorithm to convert each key into an index in memory, which is how lookups remain fast regardless of how many entries the table contains. The underlying .NET type is System.Collections.Hashtable.

The key characteristics of a PowerShell hash table are:


Creating a Hash Table​

The hash table literal syntax uses @{} — curly braces with the @ prefix. Entries use Key = Value format, separated by newlines or semicolons.


$person = @{

    Name = 'Alice'

    Age  = 30

    City = 'Osaka'

}

To verify the type PowerShell creates:


$person.GetType().FullName

# Output: System.Collections.Hashtable

Creating an empty hash table and populating it afterward:


$person = @{}

$person['Name'] = 'Alice'

$person['Age']  = 30

Inline syntax — useful when building hash tables on a single line or inside pipeline expressions:


$person = @{ Name = 'Alice'; Age = 30; City = 'Osaka' }

Accessing Values​

There are two equivalent syntaxes for reading a value from a hash table.

Bracket notation — requires a string key:


$person['Name']   # Returns: Alice

Dot notation — shorter and readable when the key is a simple identifier:


$person.Name      # Returns: Alice

Dot notation is not always available. Use bracket notation when:


$key = 'City'

$person[$key]     # Returns: Osaka

Retrieving multiple values at once — pass an array of keys inside brackets:


$person['Name', 'City']

# Returns: Alice, Osaka

This is one of the less well-known features of PowerShell hashtables and is useful for extracting subsets of data.


Adding, Updating, and Removing Entries​

Adding a new key using bracket assignment:


$person['Email'] = '[email protected]'

Adding a new key using the .Add() method — this throws an error if the key already exists, which can be useful as a safeguard:


$person.Add('Phone', '555-0100')

Updating an existing key — the same bracket and dot assignment syntax works for updates:


$person['Age'] = 31

$person.Age    = 31

Removing a key with the .Remove() method:


$person.Remove('City')

Assigning $null to a key does not remove the key — it leaves it present with a null value. Use .Remove() to delete the entry entirely.

Clearing all entries from a hash table:


$person.Clear()

While reinitializing with $person = @{} also works, .Clear() is more expressive and makes the intent explicit in the code.

Combining two hash tables with the + operator:


$defaults = @{ Timeout = 30; Retries = 3 }

$overrides = @{ Timeout = 60 }

$config = $defaults + $overrides

# $config.Timeout is 60, $config.Retries is 3

When keys overlap, the right-hand operand wins.


Checking for Keys and Values​

Testing whether a key exists with .ContainsKey() is the safest and most explicit approach:


if ($person.ContainsKey('Age')) {

    Write-Output "Age is present"

}

Do not rely on a simple truthiness check such as if ($person.Age). That expression evaluates to $false when the value is 0, $false, or an empty string — even though the key exists. This is a common source of bugs:


# Unreliable — fails silently when value is 0 or $false

if ($person.Age) { ... }



# Reliable — tests only for key presence

if ($person.ContainsKey('Age')) { ... }



# Also reliable — distinguishes between $null and absent key

if ($null -ne $person['Age']) { ... }

To search for a value when you do not know the key, use .ContainsValue():


$person.ContainsValue('Alice')   # Returns: True

The .Count property returns the number of key-value pairs:


$person.Count

Iterating Through a Hash Table​

A hash table piped to a cmdlet is treated as a single object, not a collection of its entries:


$person | Measure-Object

# Count: 1   ← the hash table itself, not its entries

To work with the entries individually, use one of the following iteration patterns.

Iterating via .Keys — the most common pattern:


foreach ($key in $person.Keys) {

    "$key : $($person[$key])"

}

Iterating via .Keys with ForEach-Object (pipeline style):


$person.Keys | ForEach-Object {

    "$_ : $($person[$_])"

}

Iterating with GetEnumerator() — yields DictionaryEntry objects, each with .Key and .Value properties. This integrates cleanly with pipeline cmdlets such as Sort-Object, Where-Object, and Select-Object:


$person.GetEnumerator() | ForEach-Object {

    "$($_.Key) : $($_.Value)"

}

To sort entries alphabetically by key:


$person.GetEnumerator() | Sort-Object Key

Iterating only values:


foreach ($value in $person.Values) {

    $value

}

BadEnumeration: Modifying a Hash Table While Iterating​

You cannot modify a hash table while enumerating its keys directly. The following code throws a BadEnumeration error:


$environments = @{

    Prod = 'SrvProd05'

    QA   = 'SrvQA02'

    Dev  = 'SrvDev12'

}



# This fails at runtime

foreach ($key in $environments.Keys) {

    $environments[$key] = 'SrvDev03'

}

# InvalidOperationException: Collection was modified; enumeration operation may not execute.

The solution is to clone the key collection before iterating. For a hash table with more than one key, use .Clone():


$environments.Keys.Clone() | ForEach-Object {

    $environments[$_] = 'SrvDev03'

}

For a hash table with exactly one key, .Clone() throws an error. Wrap in @() instead to force array conversion:


@($environments.Keys) | ForEach-Object {

    $environments[$_] = 'SrvDev03'

}

Using @($environments.Keys) is the safest pattern in all cases — it handles both single-key and multi-key hash tables without branching.


Ordered Hash Tables​

By default, hash table entries have no guaranteed order. When you enumerate them, keys may appear in any sequence. When order matters — for example, when building configuration output that should be readable, or when exporting to a structured format — use the [ordered] keyword:


$config = [ordered]@{

    Server  = 'srv01'

    Port    = 8080

    Timeout = 30

}

The underlying type becomes System.Collections.Specialized.OrderedDictionary instead of System.Collections.Hashtable. All the same operations apply — access, addition, removal, iteration — but enumeration always returns entries in insertion order.


$config.GetType().FullName

# System.Collections.Specialized.OrderedDictionary

Ordered hashtables require PowerShell 3.0 or later.


Nested Hash Tables​

A hash table value can itself be a hash table. This lets you represent structured, hierarchical data:


$server = @{

    Name    = 'web01'

    OS      = 'Windows Server 2022'

    Network = @{

        IP      = '10.0.0.5'

        Subnet  = '255.255.255.0'

        Gateway = '10.0.0.1'

    }

}

Accessing nested values chains the two access syntaxes:


$server.Network.IP

$server['Network']['IP']

$server.Network['Gateway']

Nested hash tables are common in configuration management, where each top-level key represents an environment or component, and the nested hash table holds its settings.


Storing Arrays Inside a Hash Table​

An array can be stored as the value of a hash table entry. This works because hash table entries are separated by semicolons or newlines, while array elements are separated by commas — there is no ambiguity:


$regions = @{

    West = @('Seattle', 'Portland', 'San Francisco')

    East = @('New York', 'Boston', 'Washington')

}

Accessing the array:


$regions.West          # Returns the whole array

$regions.West[0]       # Returns: Seattle

$regions['East'][1]    # Returns: Boston

The output of many cmdlets — such as Get-Process or Get-ChildItem — is an array and can be stored directly as a hash table value.


Splatting: Passing Hash Tables as Parameters​

Splatting is one of the most practical uses of hash tables in PowerShell. Instead of passing a long list of parameters inline, you pack them into a hash table and pass the whole table to a cmdlet using @ instead of $.

Without splatting, a cmdlet call with many parameters becomes difficult to read:


New-ADUser -Name 'Bob Smith' -SamAccountName 'bsmith' -GivenName 'Bob' -Surname 'Smith' -Department 'Engineering' -Enabled $true -Path 'OU=Users,DC=corp,DC=local'

With splatting:


$userParams = @{

    Name           = 'Bob Smith'

    SamAccountName = 'bsmith'

    GivenName      = 'Bob'

    Surname        = 'Smith'

    Department     = 'Engineering'

    Enabled        = $true

    Path           = 'OU=Users,DC=corp,DC=local'

}

New-ADUser @userParams

The @userParams syntax tells PowerShell to expand the hash table into named parameters. Each key becomes a parameter name; each value becomes its argument.

Splatting is not just cosmetic. It allows you to build parameters dynamically, add or remove them with conditional logic, and reuse the same parameter set across multiple calls:


$baseParams = @{ Path = 'C:\Logs'; Recurse = $true }



if ($filter) {

    $baseParams['Filter'] = $filter

}



Get-ChildItem @baseParams

$PSBoundParameters is a special automatic variable that PowerShell populates with the parameters actually passed to a function at runtime. It is itself a hash table and can be splatted directly to inner functions:


function Invoke-Wrapper {

    param($Path, $Filter, $Recurse)

    Get-ChildItem @PSBoundParameters

}

Using Hash Tables for Lookup Tables​

A hash table used as a lookup table replaces conditional logic with a direct key lookup, which is both faster and more maintainable at scale:


$exitCodes = @{

    0 = 'Success'

    1 = 'General error'

    2 = 'Misuse of shell command'

    126 = 'Command not executable'

    127 = 'Command not found'

}



$result = $exitCodes[$LASTEXITCODE]

The alternative — a chain of if/elseif or a switch block — grows linearly. A lookup table remains constant-time regardless of how many entries it contains.


Custom Pipeline Expressions​

Select-Object and Format-Table accept hash tables as calculated property definitions. This pattern lets you create new columns or properties dynamically, without modifying the original objects:


$drives = Get-PSDrive | Where-Object { $_.Used }



$totalGB = @{

    Name       = 'TotalGB'

    Expression = { [math]::Round(($_.Used + $_.Free) / 1GB, 2) }

}



$drives | Select-Object Name, $totalGB

The hash table must have a Name key (the column label) and an Expression key (a script block). You can abbreviate these to n and e for inline use:


$drives | Select-Object Name, @{ n = 'TotalGB'; e = { [math]::Round(($_.Used + $_.Free) / 1GB, 2) } }

The same pattern works with Sort-Object to sort by a calculated value:


Get-Process | Sort-Object @{ Expression = { $_.CPU / $_.WorkingSet }; Descending = $true }

Copying Hash Tables​

A simple assignment does not copy a hash table — it creates a second reference to the same object:


$original = @{ Name = 'Alice'; Age = 30 }

$copy = $original

$copy['Name'] = 'Bob'

$original['Name']   # Returns: Bob  ← the original was modified

To create a true independent copy, use the .Clone() method:


$copy = $original.Clone()

$copy['Name'] = 'Bob'

$original['Name']   # Returns: Alice  ← unaffected

.Clone() performs a shallow copy: top-level keys and their values are duplicated, but if any value is itself a reference type (an array, another hash table, an object), the copy still shares the same reference to that nested value. To perform a full deep copy of a nested structure:


$deep = [System.Management.Automation.PSSerializer]::Deserialize(

    [System.Management.Automation.PSSerializer]::Serialize($original)

)

This serializes the entire object graph to XML and deserializes it into a fully independent copy.


Exporting a Hash Table to CSV​

A hash table cannot be piped directly to Export-Csv as structured rows, because PowerShell treats the hash table itself as a single object. Use GetEnumerator() to unwrap it first:


$config.GetEnumerator() |

    Select-Object Key, Value |

    Export-Csv -Path 'C:\output\config.csv' -NoTypeInformation

Each row in the CSV file will contain one key-value pair from the hash table.


Converting Hash Tables to Custom Objects​

A hash table can be cast to [PSCustomObject] to produce an object with named properties. This is useful when you need the output to behave like a real PowerShell object — supporting property access, pipeline filtering, and formatting:


$person = @{

    Name = 'Alice'

    Age  = 30

    City = 'Osaka'

}



$obj = [PSCustomObject]$person

$obj.Name   # Returns: Alice

$obj | Select-Object Name, City

The cast preserves all key-value pairs as named properties. Note that the property order in a [PSCustomObject] cast from an unordered hash table is also unordered. Cast from an [ordered] hash table to preserve insertion order:


$obj = [PSCustomObject][ordered]@{

    Name = 'Alice'

    Age  = 30

    City = 'Osaka'

}

Case Sensitivity and .NET Hash Tables​

Standard PowerShell hash tables (@{}) are case-insensitive by default. The key Name and the key name refer to the same entry.

If you need case-sensitive keys — for example, when parsing output that distinguishes between ID and Id — create a .NET hashtable directly:


$ht = [System.Collections.Hashtable]::new([System.StringComparer]::Ordinal)

$ht['Name'] = 'Alice'

$ht['name'] = 'Bob'

$ht.Count   # Returns: 2  ← treated as different keys

Using [System.StringComparer]::OrdinalIgnoreCase (which is the PowerShell default) gives the same behavior as @{}. Using [System.StringComparer]::Ordinal makes it case-sensitive.


Hash Table Properties and Methods: Reference​

Property / MethodDescription.CountNumber of key-value pairs.KeysCollection of all keys.ValuesCollection of all values.Add(key, value)Adds a new entry; throws if key exists.Remove(key)Deletes an entry by key.Clear()Removes all entries.Clone()Creates a shallow copy.ContainsKey(key)Tests whether a key exists.ContainsValue(value)Tests whether a value exists.GetEnumerator()Returns an enumerator for pipeline use


Performance Considerations​

Hash table lookups are O(1) — constant time — regardless of table size. This makes them significantly faster than searching arrays with Where-Object when the data set is large:


# Slow for large arrays — O(n) linear scan

$match = $largeArray | Where-Object { $_.Name -eq 'Alice' }



# Fast — O(1) hash lookup

$lookup = @{}

foreach ($item in $largeArray) { $lookup[$item.Name] = $item }

$match = $lookup['Alice']

The pre-processing cost to build the lookup table is linear, but if you perform many lookups against the same data, the hash table approach pays for itself quickly.


Common Mistakes to Avoid​

Using truthiness to check key existence. if ($table.Key) returns $false when the value is 0, $false, or empty string. Use .ContainsKey() instead.

Modifying a hash table during enumeration. Iterating .Keys and writing to the same hash table throws BadEnumeration. Clone the keys with @($table.Keys) before iterating.

Assuming key order is preserved. A standard hash table has no guaranteed order. Use [ordered]@{} when order matters.

Shallow copy confusion. $b = $a makes $b an alias of $a, not a copy. Use .Clone() for a shallow copy and PSSerializer for a deep copy.

Forgetting that piping a hash table sends it as one object. Pipe .GetEnumerator() if you want to work with individual entries in the pipeline.

Using .Set_Item() when bracket assignment suffices. $table['Key'] = 'Value' does the same thing and is the idiomatic syntax.


Best Practices Summary​

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Arrays

Next

Type Accelerators