Hashtables, also known as associative arrays or dictionary objects, are a powerful data structure in PowerShell. Unlike standard arrays, which use numeric indices, hashtables use keys to associate with values. This makes them ideal for storing and retrieving data in a structured way.
1. What is a Hashtable?
A hashtable is a collection of key-value pairs, where each key is unique and maps to a specific value. Think of it like a dictionary:
Key: The word you look up (e.g., "CA").
Value: The definition or associated data (e.g., "California").
2. Creating a Hashtable
To create a hashtable, use the @{} syntax. Each key-value pair is separated by a semicolon (;).
$States.ContainsKey("VA") # Returns $true if "VA" exists
$States.ContainsValue("Virginia") # Returns $true if "Virginia" exists
$States.CA # Returns "California"
$States.Add("CO", "Colorado")
$States.Remove("CO")
$States.Clear()
# Save hashtable to a file
$Config = @{
Server = "localhost"
Port = 8080
LogLevel = "Verbose"
}
$Config | Export-Clixml -Path "config.psd1"
# Load hashtable from a file
$LoadedConfig = Import-PowerShellDataFile -Path "config.psd1"