PowerShell: How to Sort Object Based on Custom Order


Often you may want to sort an object based on a custom order in PowerShell.

You can use the following basic syntax to do so:

$my_order = "Nets", "Lakers", "Mavs"
Import-Csv nba_data.csv | Sort { $my_order.IndexOf($_.team) }

This particular example imports the rows from the CSV file named nba_data.csv and then sorts the rows based on the following order of values in the team column of the file:

  • Nets
  • Lakers
  • Mavs

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

Example: How to Sort Object Based on Custom Order in PowerShell

Suppose we have a file named nba_data.csv in our current directory that contains information about various basketball players.

We can use the Import-Csv cmdlet to first view the contents of this file:

Now suppose that we would like to sort the rows of this CSV file based on the values in the team column in the following custom order: Nets, Lakers, Mavs.

We can use the following syntax to do so:

$my_order = "Nets", "Lakers", "Mavs"
Import-Csv nba_data.csv | Sort { $my_order.IndexOf($_.team) }

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

PowerShell custom sort

We can see that the rows in the table are sorted based on the custom order that we specified for the values in the team column.

Feel free to use similar syntax to sort your own object based on a specific custom order.

Note: You can find the complete documentation for the Sort cmdlet in PowerShell here.

Related Tutorials

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

PowerShell: How to Sort a Table with Format-Table
PowerShell: How to Use Sort-Object with Multiple Properties
PowerShell: How to Sort Files in Folder by Size

Leave a Reply