Creating a Dictionary in PowerShell
Most of the time, an ordinary
PowerShell hashtable (which is created with
@{…}
) is sufficient if key/value pairs need to be stored in PowerShell.
However, if an explicit Dictionary<TKey, TValue>
is needed, such an object can be created like so:
$dict = new-object 'System.Collections.Generic.Dictionary[String, Int]'
$dict['four'] = 4
$dict['nine'] = 9
$dict['five'] = 5
# $dict[ 7 ] ='seven' # Error: Cannot convert value "seven" to type "System.Int32" …
echo $dict['nine']
9
Iterating over a Dictionary's keys in PowerShell
The following example tries to demonstrate how it is possible to iterate over the keys of a Dictionary<TKey,TValue>
object in PowerShell.
$dict = new-object 'System.Collections.Generic.Dictionary[String, String]'
$dict['Fruit'] = 'Orange'
$dict['City' ] = 'Paris'
$dict['Make' ] = 'BWM'
foreach ($key in $dict.keys) {
"$key -> $($dict[$key])"
}
Iterating over key/value pairs in PowerShell
Because a
Dictionary[TKey, TValue]
implements the
IEnumerable<T>
interface, the
GetEnumerator()
is implemented which allows to iterate over the dictionary's key/value pairs. In the
foreach $item in …
statement, the variable
$item
has the two properties
key
and
value
that allow to access the respective values:
$dict = new-object 'System.Collections.Generic.Dictionary[String, Int32]'
$dict['forty-two' ] = 42
$dict['ninety-nine'] = 99
$dict['minus one' ] = -1
foreach ($item in $dict.GetEnumerator()) {
"{0,-11}: {1}" -f $item.key, $item.value
}
#
# forty-two : 42
# ninety-nine: 99
# minus one : -1