Hashtables and key order Hashtables and key order powershell powershell

Hashtables and key order


There is no built-in solution in PowerShell V1 / V2. You will want to use the .NETSystem.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> $orderName                           Value----                           -----Switzerland                    BernSpain                          MadridItaly                          RomeGermany                        Berlin

In PowerShell V3 you can cast to [ordered]:

PS> [ordered]@{"Switzerland"="Bern"; "Spain"="Madrid"; "Italy"="Rome"; "Germany"="Berlin"}Name                           Value----                           -----Switzerland                    BernSpain                          MadridItaly                          RomeGermany                        Berlin


You can use an ordered dictionary instead:

Like this:

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


You can give one sequential key as you add elements:

$hashtable = @{}$hashtable[$hashtable.count] = @("Switzerland", "Bern")$hashtable[$hashtable.count] = @("Spain", "Madrid")$hashtable[$hashtable.count] = @("Italy", "Rome")$hashtable[$hashtable.count] = @("Germany", "Berlin")$hashtable

Then, you can get elements sorted by the key:

echo "`nHashtable keeping the order as they were added"foreach($item in $hashtable.getEnumerator() | Sort Key){    $item}