PowerShell Sort-Object and Hashtables

Maybe this will be obvious for everyone but I would like to share it anyway because I had some WTFs today 🙂

I had an array of objects with anonymous type and I wanted to sort them by some property.

$array = @(@{ Description = "bbb"; Value = 123 }, @{ Description = "aaa"; Value = 345 })

$array | Sort-Object -Property Description

I was surprised but last command did not work as expected. My array still remained unsorted.

Name                           Value
----                           -----
Value                          123
Description                    bbb
Value                          345
Description                    aaa

After some head-scratch finally I found the right way.

$array | Sort-Object { $_.Description }
Name                           Value
----                           -----
Value                          345
Description                    aaa
Value                          123
Description                    bbb

The problem with first approach was that I have been using hashtables (@{ … }) and property Description is not a real property of that object.

Another approach would be to convert objects from HashTables to real anonymous objects

$array = @(@{ Description = "bbb"; Value = 123 }, @{ Description = "aaa"; Value = 345 }) | ForEach-Object { New-Object PSObject -Property $_ }

$array | Sort-Object -Property Description
Value Description
 ----- -----------
   345 aaa
   123 bbb
Advertisements

About mnaoumov

Senior .NET Developer in Readify
This entry was posted in Uncategorized and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s