How to Use Hashtable in PowerShell: Syntax and Examples
In PowerShell, a
hashtable is a collection of key-value pairs created using @{} syntax. You add items by specifying keys and values inside the braces, and access values by their keys using $hashtable['key'].Syntax
A hashtable in PowerShell is defined using @{} with key-value pairs inside. Each key is followed by an equals sign and its value. You can access values by using the key inside square brackets after the hashtable variable.
- @{}: Defines the hashtable.
- key = value: Adds a key-value pair.
- $hashtable['key']: Retrieves the value for the key.
powershell
$hashtable = @{ Key1 = 'Value1'; Key2 = 'Value2' }
$value = $hashtable['Key1']Example
This example shows how to create a hashtable, add key-value pairs, and access a value by its key.
powershell
$person = @{ Name = 'Alice'; Age = 30; City = 'Seattle' }
Write-Output $person['Name']
Write-Output $person['Age']
# Adding a new key-value pair
$person['Occupation'] = 'Engineer'
Write-Output $person['Occupation']Output
Alice
30
Engineer
Common Pitfalls
Common mistakes include using parentheses instead of braces to create a hashtable, forgetting quotes around string keys when accessing values, or trying to access keys that do not exist.
Always use @{} to create hashtables, and use quotes around keys when accessing values if the key is a string.
powershell
# Wrong: Using parentheses instead of braces $wrong = ( Key = 'Value' ) # This creates a different object, not a hashtable # Right: Use braces $right = @{ Key = 'Value' } # Wrong: Accessing key without quotes (works only if key is a valid variable name) $value = $right[Key] # May cause error or unexpected result # Right: Use quotes $value = $right['Key']
Quick Reference
Remember these quick tips when working with hashtables in PowerShell:
- Use
@{}to create a hashtable. - Keys are case-insensitive strings by default.
- Access values with
$hashtable['key']. - Add or update keys by assignment:
$hashtable['newKey'] = 'newValue'. - Use
GetEnumerator()to loop through all key-value pairs.
Key Takeaways
Create hashtables using @{} with key = value pairs inside.
Access values by keys using $hashtable['key'] with quotes around string keys.
Add or update entries by assigning a value to a key like $hashtable['key'] = value.
Avoid using parentheses instead of braces to define hashtables.
Use GetEnumerator() to loop through all keys and values in a hashtable.