Monthly Archive

Categories

Sorting a hash table

There is a really good PowerShell script for working with indexed files - scans or photos and renumbering to cope with missing numbers available from http://www.tellingmachine.com/post/2008/07/Renaming-a-series-of-indexed-files-with-Powershell.aspx

One point at the end of the post is about sorting hash tables.  This is not intuitive as piping the hash table into sort does not work.  You need to use the GetEnumerator() before trying to sort like this

PS> $a = @{}
PS> $a[[int]1] = "dir scan0001.txt"
PS> $a[[int]11] = "dir scan0011.txt"
PS> $a[[int]3] = "dir scan0003.txt"
PS> $a

Name                           Value
----                           -----
3                              dir scan0003.txt
1                              dir scan0001.txt
11                             dir scan0011.txt

PS> $a.getEnumerator() | Sort Key -Descending

Name                           Value
----                           -----
11                             dir scan0011.txt
3                              dir scan0003.txt
1                              dir scan0001.txt

PS> $a.getEnumerator() | Sort Name -Descending

Name                           Value
----                           -----
11                             dir scan0011.txt
3                              dir scan0003.txt
1                              dir scan0001.txt

Create a hash table as shown.  Use the getEnumerator() method and pipe into sort.  Sorted!

 

Share this post :

Technorati Tags: PowerShell

Leave a Reply