PowerShell: How to Sort a Table with Format-Table


Often you may want to sort the values in a table created by the Format-Table cmdlet in PowerShell.

You can use the following basic syntax to do so:

Dir $my_folder | Sort -Property Name | Format-Table

This particular example uses the Dir statement to extract all files and folders from the path specified by the $my_folder variable, then uses Sort to sort the files and folders based on the Name property, then uses the Format-Table cmdlet to pipe the results to a neatly formatted table.

The following example shows how to use this syntax in practice.

Example: How to Sort a Table with Format-Table in PowerShell

Suppose we have a directory located at the following path:

  • c:\users\bobbi\data1

Suppose we use the following syntax to list all files and folders in this directory:

$my_folder = "c:\users\bobbi\data1"
Dir $my_folder | Format-Table

The following screenshot shows how to use this syntax in practice:

By default, the output is shown with all folders listed first, followed by all of the files.

Suppose that we would like to instead show the output with all files and folders listed in alphabetical order, from A to Z.

We can use the following syntax to do so:

$my_folder = "c:\users\bobbi\data1"
Dir $my_folder | Sort -Property Name | Format-Table

The following screenshot shows how to use this syntax in practice:

PowerShell format-table sort

We can see that the rows in the table are now sorted in alphabetical order from A to Z based on the string values in the Name column.

Note that you could also use the -descending operator if you would instead like to sort the rows in descending order from Z to A based on the string values in the Name column:

$my_folder = "c:\users\bobbi\data1"
Dir $my_folder | Sort -Property Name -descending | Format-Table

The following screenshot shows how to use this syntax in practice:

PowerShell format-table sort in descending order

The rows in the table are now sorted in descending alphabetical order from Z to A based on the string values in the Name column.

Note: You can find the complete documentation for the Format-Table cmdlet in PowerShell here.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Check if Hash Table Contains Specific Key
PowerShell: How to Remove Elements from a Hash Table
PowerShell: How to Iterate Over a Hash Table

Leave a Reply