Powershell, add items in order to hashtable

Viewed 597

I have the following sample script

$aDomains = @{}

$aDomains['a-test.nl'] = @{}
$aDomains['b-test.nl'] = @{}
$aDomains['c-test.nl'] = @{}
$aDomains['d-test.nl'] = @{}
$aDomains['e-test.nl'] = @{}

$aDomains

It seems very straight forward, but if I run this script, the output is very unexpected:

$aDomains


Name                           Value                                                                                
----                           -----                                                                                
e-test.nl                      {}                                                                                   
d-test.nl                      {}                                                                                   
b-test.nl                      {}                                                                                   
a-test.nl                      {}                                                                                   
c-test.nl                      {} 

How can I get the output to match the order of items being added? I do need to use the @{} on all instances due to what happens next in the script.

Also, adding this in the script has no effect at all:

$aDomains = $aDomains | Sort-Object
2 Answers

By default a hashtable is not ordered, as you saw. Since PowerShell 3.0, you can make a hashtable ordered, in which case it will keep the order.

See the below example:

$aDomains = [ordered] @{}

$aDomains['e-test.nl'] = @{}
$aDomains['a-test.nl'] = @{}
$aDomains['b-test.nl'] = @{}
$aDomains['c-test.nl'] = @{}
$aDomains['d-test.nl'] = @{}
$aDomains['e-test.nl'] = @{}

$aDomains

Name                           Value                                                                                
----                           -----                                                                                
e-test.nl                      {}                                                                                   
a-test.nl                      {}                                                                                   
b-test.nl                      {}                                                                                   
c-test.nl                      {}                                                                                   
d-test.nl                      {}  

As you can see, the e-test.nl is in the list twice, but only added once at the top, so it does pertain the order of added, and won't add something twice. To get this to work, add the [ordered] tag to the beginning of the hashtable assignment.

Small sidenode though. If you use the .ContainsKey() function, this needs to be changed to .Contains()

If we unwrap this object into it’s individual elements,then we can sort it.

$aDomains= $aDomains.GetEnumerator() | Sort-Object -Property Name
Related