Over the weekend I received a nice comment from a reader who came across an old post of mine on turning an object into a hash table. He wanted to add a comment but my blog closes comments after a period of time. But I thought it was worth sharing, especially for those of you still getting started with PowerShell. The comment was on how to sort a hash table.
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
Let's say you have a simple hash table like this:
$hash = @{ Name="Jeff" Size = 123 Color = "Green" Computer = "Yoga2Pro" }
And is displayed like this:
PS C:\scripts> $hash Name Value ---- ----- Color Green Name Jeff Computer Yoga2Pro Size 123
To sort on the keys, you can use the GetEnumerator() method which is part of every hash table object. This method creates a System.Collections.DictionaryEntry object for each item in the hash table.
PS C:\scripts> $hash.GetEnumerator() | get-member TypeName: System.Collections.DictionaryEntry Name MemberType Definition ---- ---------- ---------- Name AliasProperty Name = Key Equals Method bool Equals(System.Object obj) GetHashCode Method int GetHashCode() GetType Method type GetType() ToString Method string ToString() Key Property System.Object Key {get;set;} Value Property System.Object Value {get;set;}
This means you can sort on any property.
PS C:\scripts> $hash.GetEnumerator() | sort key Name Value ---- ----- Color Green Computer Yoga2Pro Name Jeff Size 123 PS C:\scripts> $hash.GetEnumerator() | sort value Name Value ---- ----- Size 123 Color Green Name Jeff Computer Yoga2Pro
By the way, starting in PowerShell 3.0, you could "pre-sort" the hash table by defining it as 'ordered'.
$hash = [ordered]@{ Name="Jeff" Computer = "Yoga2Pro" Color = "Green" Size = 123 }
Now the hash table will always be sorted in the order you defined the entries.
PS C:\scripts> $hash Name Value ---- ----- Name Jeff Computer Yoga2Pro Color Green Size 123
Although, if you want to sort you still can.
PS C:\scripts> $hash.GetEnumerator() | sort name -Descending Name Value ---- ----- Size 123 Name Jeff Computer Yoga2Pro Color Green
Have a great week and I hope you get things sorted out.
The .GetEnumerator() is such a handy thing. Thanks for writing it up.
I found this nugget on a blog: Out-String -Stream | Sort-Object
If you pipe a object to it you get a nice sorted hash table-looking output.
For example:
get-service spooler | select * | Out-String -Stream | Sort-Object
It skips the hash table all together but is useful for looking at the properties of an object in a sorted order. It works great for an Office 365 mailbox which has a lot of properties. The get-mailbox cmdlet does not sort the properties so it’s a pain to find things.
Thank you for all your blog entries. They are a big help as there is so much to learn in PowerShell.
That is a handy tip. Thanks.