PowerShell – hashtable and custom object array about iteration
I often write lists of things and enumerate them to perform some get / set
I hate enumerating hash tables because whenever I have to, I have to bend back to use hash table objects
$hashtablelistofitems = @{} $hashtablelistofitems.add("i'm a key","i'm a value") foreach ($item in $hashtablelistofitems.keys) { $item $hashtablelistofitems.item($item) }
Instead, I usually revert to a one - dimensional array of custom objects with two noteproperties
$array = @() $listofitems = "" | select key,value $listofitems.key = "i'm a key" $listofitems.value = "i'm a value" $array += $listofitems foreach ($item in $listofitems) { $item.key $item.value }
Why should I use a hash table on this method? Just because it only guarantees a single value for each key?
Solution
If you want to store a list of key values without creating an array containing a custom object with two properties (key / value), you should use a hash table for two main reasons:
>You may want to pass the hash table to the function that expects the hash table. > Hashtable is a built - in PowerShell type known to all users Your second method is more difficult for other users to read / maintain
Note: you can iterate the hash table by calling the getenumerator() function, which is almost the same as your method:
foreach ($item in $listofitems.GetEnumerator()) { $item.key $item.value }
In addition, the hash table comes with convenient methods you may want to use:
@{} | Get-Member | Where-Object MemberType -eq Method | Select Name
Output:
Name ---- Add Clear Clone Contains ContainsKey ContainsValue CopyTo Equals GetEnumerator GetHashCode GetObjectData GetType OnDeserialization Remove ToString