Hashtables and key order

hashtable, powershell, powershell-2.0, sorting

Solution

There is no built-in solution in PowerShell V1 / V2. You will want to use the .NET `System.Collections.Specialized.OrderedDictionary`:

$order = New-Object System.Collections.Specialized.OrderedDictionary
$order.Add("Switzerland", "Bern")
$order.Add("Spain", "Madrid")
$order.Add("Italy", "Rome")
$order.Add("Germany", "Berlin")


PS> $order

Name                           Value
----                           -----
Switzerland                    Bern
Spain                          Madrid
Italy                          Rome
Germany                        Berlin

In PowerShell V3 you can cast to [ordered]:

PS> [ordered]@{"Switzerland"="Bern"; "Spain"="Madrid"; "Italy"="Rome"; "Germany"="Berlin"}

Name                           Value
----                           -----
Switzerland                    Bern
Spain                          Madrid
Italy                          Rome
Germany                        Berlin

Problem

Is there a way to keep the order of keys in a hashtable as they were added? Like a push/pop mechanism. Example: ``` $hashtable = @{} $hashtable.Add("Switzerland", "Bern") $hashtable.Add("Spain", "Madrid") $hashtable.Add("Italy", "Rome") $hashtable.Add("Germany", "Berlin") $hashtable ``` I want to retain the order in which I've added the elements to the hashtable.

Original source

Related problems