Hashtables and Splatting
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 (;
).
Example:
$States = @{
"CA" = "California"
"FL" = "Florida"
"VA" = "Virginia"
"MD" = "Maryland"
}
Key Points:
Keys and values can be of any data type.
Keys must be unique within the hashtable.
Use semicolons to separate key-value pairs if they are on the same line.
3. Accessing Hashtable Data
Displaying the Entire Hashtable
To display all key-value pairs:
$States
Displaying Keys or Values
To display only the keys or values:
$States.Keys # Display all keys
$States.Values # Display all values
Checking for Keys or Values
To check if a specific key or value exists:
$States.ContainsKey("VA") # Returns $true if "VA" exists
$States.ContainsValue("Virginia") # Returns $true if "Virginia" exists
Accessing Values
To retrieve the value associated with a key:
$States.CA # Returns "California"
4. Modifying a Hashtable
Adding a Key-Value Pair
To add a new key-value pair:
$States.Add("CO", "Colorado")
Removing a Key-Value Pair
To remove a key-value pair:
$States.Remove("CO")
Clearing the Hashtable
To remove all key-value pairs:
$States.Clear()
5. Practical Uses of Hashtables
Configuration Files
Hashtables are often used to store configuration settings. You can save a hashtable to a .psd1
file and load it later using Import-PowerShellDataFile
.
Example:
# 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"
Filtering Event Logs
The Get-WinEvent
cmdlet uses hashtables for filtering event logs.
Example:
$filter = @{
LogName = "Security"
ID = 4624
}
Get-WinEvent -FilterHashtable $filter
6. Splatting: Simplifying Command Parameters
Splatting is a technique where you use a hashtable to pass multiple parameters to a cmdlet. This makes your code cleaner and easier to read.
Example: Splatting with Get-WinEvent
$ParamArgs = @{
ComputerName = "Member"
LogName = "Security"
MaxEvents = 100
ErrorAction = "Stop"
}
$Events = Get-WinEvent @ParamArgs
Example: Splatting with New-NetIPsecRule
$Splat = @{
DisplayName = 'IPsecRuleName'
Phase1AuthSet = 'AuthPro47'
InboundSecurity = 'Require'
OutboundSecurity = 'Request'
Protocol = 'TCP'
LocalAddress = 'Any'
LocalPort = 'Any'
RemoteAddress = '10.0.0.0/8'
RemotePort = @('3389', '139', '445', '21')
Profile = 'Any'
InterfaceType = 'Any'
Enabled = 'True'
}
New-NetIPsecRule @Splat
Key Points:
Use
@
instead of$
when passing the hashtable to a cmdlet.Splatting is especially useful for cmdlets with many parameters.
7. Advanced Hashtable Features
Nested Hashtables
Hashtables can contain other hashtables, allowing you to create complex data structures.
Example:
$Config = @{
Server = @{
Name = "localhost"
Port = 8080
}
Logging = @{
Level = "Verbose"
Path = "C:\Logs"
}
}
$Config.Server.Name # Returns "localhost"
Iterating Over Hashtables
You can loop through a hashtable using foreach
.
Example:
foreach ($key in $States.Keys) {
Write-Output "$key = $($States[$key])"
}
Last updated