HashTable
HashTable is essentially System.Collections.HashTable, the non-generic version of Dictionary<,>.
@{} -is [System.Collections.IDictionary] # True
@{} -is [System.Collections.HashTable] # True2
TIP
HashTable serves as more like a dictionary with syntax sugar, if you want it to be more like object literal, use [pscustomobject].
Creation
PowerShell has builtin syntax for creating a HashTable. Inline declaration requires ; to distinguish key-value pairs.
$foo = @{
Name = 'foo'
Age = 18
}
$foo = @{ Name = 'foo'; Age = 18 }2
3
4
5
6
Ordered HashTable
[ordered] is a mark can be used when creating HashTable literal, it makes sure that all entries are ordered as in declaration and subsequent appending.
([ordered]@{
C = 'C'
B = 'B'
A = 'A'
}).Keys # C B A #
@{
C = 'C'
B = 'B'
A = 'A'
}.Keys # B C A #2
3
4
5
6
7
8
9
10
11
NOTE
[ordered] can not be used as type, but it's indeed a System.Collections.Specialized.OrderedDictionary.
([ordered]@{}).GetType().FullName # System.Collections.Specialized.OrderedDictionaryAccess Values
You can access value of one or more keys by indexer.
$foo['Name'] # foo
$foo['Name', 'Age'] # @('foo', 18)2
NOTE
PowerShell uses TryGetValue when accessing value with indexer syntax for IDictionary types, so it never throw.
. accessor would also works as long as there's no duplicated Extended Property with the same name of the key you passed.
$foo.Name # foo
$foo.'Name'
$name = 'name'
$foo.$name2
3
4
TIP
Always use indexer to access value of a HashTable. . will prefer Extended Property that might be unexpected.
NOTE
Key in HashTable can be any type. So if the key is not a singular type, you'll have to extract the key from Keys first and then access the value by the key.
Merging
@{ foo = 123; bar = '123' } + @{ baz = 234 }WARNING
+ will throw if the two have any duplicated key.