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