Friday, September 25, 2009

Sorting hashtable in Powershell

I am using hashtables (or dictionaries) more and more in Powershell – once I figured out that syntax $Hashtable.Key works, it turned out to be extremely useful as something similar to custom class.

However I run into an issue (maybe bug?) with sorting hashtables:

PS C:\> $X.Martin = "Zugec"
PS C:\> $X.Kamila = "Vlasakova"
PS C:\> $X.Filip = "Puntik"
PS C:\> $X.Tereza = "Liska"
PS C:\> $X | Sort Name

Name                           Value
----                           -----
Filip                          Puntik
Kamila                       Vlasakova
Tereza                      Liska
Martin                       Zugec

As you can see, output is not sorted. After a while I tried to use raw method that is used in .NET:

PS C:\> $X.psbase.GetEnumerator() | Sort Name

Name                           Value
----                           -----
Filip                          Puntik
Kamila                       Vlasakova
Martin                       Zugec
Tereza                      Liska

As you can see, everything is sorted out correctly in this case. Another scenario where you could use GetEnumerator is if you want to handle name (key) and value:

PS C:\> $X.psbase.GetEnumerator() | Where {$_.Name -eq "Martin"}

Name                           Value
----                           -----
Martin                         Zugec

Without using enumerator, you got access only to values.

1 comment:

Frank-Peter Schultze said...

Hashtables are quite powerful. For example, I wrote a bunch of functions to manage content of INI files (see http://www.fpschultze.de/news+article.storyid+119.htm)