PowerShell: How to Use Sort-Object with Multiple Properties


Often you may want to import data files into PowerShell and then sort the data by multiple properties.

You can use the following basic syntax to do so:

Import-Csv $my_file | Sort-Object -Property @{Expression={[int]$_.points}}, @{Expression={[int]$_.assists} ;Descending=$true}

This particular example imports the file specified at the path in the $my_file object, then sorts the rows in ascending order based on the values in the points column, then in descending order based on the values in the assists column.

Note: We used [int] to cast the points and assists columns to integer data types before sorting.

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

Example: Use Sort-Object to Sort by Multiple Properties in PowerShell

Suppose we have a CSV file saved at the following location:

  • c:\users\bobbi\nba_data.csv

Suppose we use the Import-Csv cmdlet to view the contents of this entire file:

The file contains three columns that show the team, points and assists for various basketball players.

Suppose that we would like to sort the rows in the following manner:

  • First, in ascending order by the points column.
  • Then, in descending order by the assists column.

We can use the following syntax to do so:

Import-Csv $my_file | Sort-Object -Property @{Expression={[int]$_.points}}, @{Expression={[int]$_.assists} ;Descending=$true}

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

PowerShell Sort-Object multiple properties

Notice that the rows are sorted by points in ascending order, then by assists in descending order.

Note #1: Since the Sort-Object cmdlet sorts values in ascending order by default, we only have to use Descending=$true if we instead want an object to be sorted in descending order.

Note #2: In this example we sorted by two properties, but you can use similar syntax to sort by as many properties as you would like.

Related Tutorials

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

PowerShell: How to Use Group-Object with Multiple Properties
PowerShell: How to Find Duplicate Values in Array
PowerShell: How to Compare Two Arrays

Leave a Reply