0

In a nutshell I'm trying to get what would be the output of this command to run.

Get-Process | Format-Table | sort-object Handles

Yes, I know you usually sort BEFORE Format-Table, but in this case I've created a hash-table within the Format-Table command that needs to be sorted. The problem is, there is no way to sort with Format-Table that I can figure out.

I also considered trying to output the FT to CSV and then massaging it but that didn't work for me either.

I'm expecting to get a sorted table.

bbrendon
  • 416
  • 3
  • 8
  • 3
    No that will not work because `Format-Table`'s intent is simply to display objects as Table to the console not mean to be sorted or exported – Santiago Squarzon Dec 19 '22 at 02:37

1 Answers1

0

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.

mklement0
  • 382,024
  • 64
  • 607
  • 775