PowerShell by Example: Hashtables
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.Keyprovides 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
KeysandValuesproperties 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
@{} creates hashtable with key-value pairs.$config.Keys returns collection of all keys for iteration.[ordered]@{} creates OrderedDictionary preserving insertion order.
