Sort a PowerShell hash table on a property of the value Sort a PowerShell hash table on a property of the value powershell powershell

Sort a PowerShell hash table on a property of the value


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.


I was using a hash table as a frequency table, to count the occurrence of words in filenames.

$words = @{}get-childitem *.pdf | foreach-object -process {    $name = $_.name.substring($_.name.indexof("-") + 1, $_.name.indexof(".") - $_.name.indexof("-") - 1)    $name = $name.replace("_", " ")    $word = $name.split(" ")[0]    if ( $words.contains($word) ){        $words[$word] = $words[$word] + 1     }else{        $words.add($word, 1)    }}$words.getenumerator() | sort-object -property value

It's that last line that does the magic, sorting the hash table on the value(frequency).