You should use a hash table if you want to save a list of key values, and not create an array containing a custom object with two properties (key / values), mainly for two reasons:
- You might want to pass your hash table to a function that expects a hash table.
- Hashtable is the built-in PowerShell type that users are aware of. Your second approach is harder to read / maintain for other users.
Note: You can iterate over a hash table in much the same way as your approach by calling the GetEnumerator() function:
foreach ($item in $listofitems.GetEnumerator()) { $item.key $item.value }
In addition, the hash table comes with convenient methods that you can 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
source share