Hash Tables
Hash tables (also called hashtables or dictionaries) are key-value pair collections in PowerShell, similar to associative arrays or dictionaries in other languages.
1. Creating Hash Tables
- Basic syntax:powershell
$hash = @{ Name = 'Alice' Age = 30 City = 'New York' } - Empty hash table:powershell
$empty = @{} - Ordered hash table (preserves insertion order):powershell
$ordered = [ordered]@{ First = 1 Second = 2 Third = 3 }
2. Accessing Values
powershell
$hash['Name'] # Alice
$hash.Name # Alice (property syntax)
$hash.Age # 30
$hash['NonExistent'] # Returns $null if key doesn't exist3. Adding and Modifying
powershell
$hash['Email'] = 'alice@example.com' # Add new key
$hash.Age = 31 # Modify existing key
$hash.Add('Phone', '123-456-7890') # Add using method4. Removing Keys
powershell
$hash.Remove('City') # Remove by key
$hash.Clear() # Remove all keys5. Checking Existence
powershell
$hash.ContainsKey('Name') # True
$hash.ContainsValue('Alice') # True
'Name' -in $hash.Keys # True6. Iteration
powershell
# Iterate keys
foreach ($key in $hash.Keys) {
"$key = $($hash[$key])"
}
# Iterate key-value pairs
$hash.GetEnumerator() | ForEach-Object {
"$($_.Key) = $($_.Value)"
}7. Converting to Objects
powershell
[pscustomobject]$hash # Convert to custom object
$hash | ConvertTo-Json # Convert to JSON8. Nested Hash Tables
powershell
$nested = @{
User = @{
Name = 'Alice'
Age = 30
}
Settings = @{
Theme = 'Dark'
Language = 'en'
}
}
$nested.User.Name # Alice9. Common Use Cases
- Configuration storage
- Function parameters (splatting)
- Grouping data
- Lookup tables
10. Performance Notes
- Hash tables provide O(1) average lookup time
- For large datasets, consider using
[System.Collections.Generic.Dictionary[K,V]]for better performance