I've created a hash-table within the Format-Table
command that needs to be sorted
By definition, you can not output a hashtable via any of the -Format-*
cmdlets:
Format-*
cmdlets emit output objects whose sole purpose is to provide formatting instructions to PowerShell's for-display output-formatting system. In short: only ever use Format-*
cmdlets to format data for display, never for subsequent programmatic processing - see this answer for more information.
Assuming you've used calculated properties, with Format-Table
, use them with Select-Object
instead, which produces data output, namely in the form of [pscustomobject]
instances whose properties you can sort by, via Sort-Object
.
For instance, the following creates custom objects with .Name
and .MemUse
properties and sorts by the latter, then outputs the top 10 results:
Get-Process |
Select-Object Name, @{ Name = 'MemUse'; Expression = 'WorkingSet64' } |
Sort-Object -Descending MemUse |
Select-Object -First 10
Inverting the logic and letting Sort-Object
operate on the original objects output by Get-Process
is more efficient:
Get-Process |
Sort-Object -Descending WorkingSet64 |
Select-Object -First 10 |
Select-Object Name, @{ Name = 'MemUse'; Expression = 'WorkingSet64' }
If you only care about for-display output, you can replace Select-Object Name, ...
with Format-Table -Name, ...
or Format-List -Name, ...
, which illustrates an important point: Format-*
calls should generally only come last in a pipeline.