BudiBadu Logo
Samplebadu

PowerShell by Example: Hashtables

PowerShell 7

Working with key-value pairs through this sample code demonstrating hashtable creation with @{} syntax, dot notation and bracket notation for value access, ordered hashtables for insertion order preservation, and key enumeration.

Code

# Creating a hashtable
$config = @{
    AppName = "MyScript"
    Version = 1.0
    Path    = "C:\Logs"
}

# Accessing values
Write-Host "App: $($config.AppName)"
Write-Host "Path: $($config['Path'])"

# Adding/Modifying
$config.Author = "John Doe"
$config["Version"] = 1.1

# Iterating
foreach ($key in $config.Keys) {
    Write-Host "$key = $($config[$key])"
}

# Ordered Hashtable (preserves insertion order)
$ordered = [ordered]@{
    First  = 1
    Second = 2
}

Explanation

Hashtables in PowerShell are dictionaries that store key-value pairs, created using the @{} syntax. Keys are typically strings but can be any object type, while values can be any object including strings, numbers, arrays, other hashtables, or custom objects. Each key in a hashtable must be unique, and hashtables provide efficient O(1) insertion, retrieval, and deletion operations based on key hashing.

Hashtable characteristics include:

  • Dot notation $hash.Key provides convenient property-style access
  • Bracket notation $hash['Key'] allows programmatic key access with variables
  • Standard hashtables are unordered with no guaranteed key sequence
  • Ordered hashtables using [ordered]@{} maintain insertion order
  • The Keys and Values properties return collections for iteration
  • GetEnumerator() method provides key-value pair enumeration

New keys can be added by simple assignment to a non-existent key name, and existing values are modified the same way. Hashtables are commonly used for configuration data, parameter splatting with @ operator, and creating custom objects before the [PSCustomObject] type accelerator. The ContainsKey() method checks for key existence, while Remove() deletes key-value pairs.

Code Breakdown

2
@{} creates hashtable with key-value pairs.
10
Dot notation and bracket notation both access values by key.
17
$config.Keys returns collection of all keys for iteration.
22
[ordered]@{} creates OrderedDictionary preserving insertion order.