Sort a PowerShell hash table on a property of the value

hashtable, powershell, sorting

Solution

Sort-Object accepts a property name or a script block used to sort. Since you're trying to sort on a property of a property, you'll need to use a script block:

Write-Host "Ascending"
$h.GetEnumerator() | 
    Sort-Object { $_.Value.SortOrder } | 
    ForEach-Object {  Write-Host $_.Value.SortOrder }

Write-Host "Descending"
$h.GetEnumerator() |
    Sort-Object { $_.Value.SortOrder } -Descending |
    ForEach-Object { Write-Host $_.Value.SortOrder }

You can filter using the Where-Object cmdlet:

Write-Host "Ascending"
$h.GetEnumerator() | 
    Where-Object { $_.Name -ge 2 } |
    Sort-Object { $_.Value.SortOrder } | 
    ForEach-Object {  Write-Host $_.Value.SortOrder }

You usually want to put `Where-Object` before any `Sort-Object` cmdlets, since it makes sorting faster.

Problem

I'm having an issue sorting a hash table. I've broken down my code to just bare necessities so as not to overwhelm anyone with my original script. ``` Write-Host "PowerShell Version = " ([string]$psversiontable.psversion) $h = @{} $Value = @{SortOrder=1;v1=1;} $h.Add(1, $Value) $Value = @{SortOrder=2;v1=1;} $h.Add(2, $Value) $Value = @{SortOrder=3;v1=1;} $h.Add(3, $Value) $Value = @{SortOrder=4;v1=1;} $h.Add(4, $Value) Write-Host "Ascending" foreach($f in $h.GetEnumerator() | Sort-Object Value.SortOrder) { Write-Host $f.Value.SortOrder } Write-Host "Descending" foreach($f in $h.GetEnumerator() | Sort-Object Value.SortOrder -descending) { Write-Host $f.Value.SortOrder } ``` The output is ``` PowerShell Version = 3.0 Ascending 2 1 4 3 Descending 2 1 4 3 ``` I'm sure this is just a simple case of not knowing the correct usage of `Sort-Object`. The sort works correctly on `Sort-Object Name` so maybe it has something to do with not knowing how to handle the `Value.SortOrder`?

Original source