Learning PowerShell Sort-Object with Examples

Published:20 July 2023 - 4 min. read

Nicholas Xuan Nguyen Image

Nicholas Xuan Nguyen

Read more tutorials by Nicholas Xuan Nguyen!

Today’s sponsor is n8n, the AI-native workflow automation tool built for ITOps and DevSecOps. With 100+ templates to get you started quickly and a powerful visual editor, you can automate complex workflows without giving up control. Check it out here.

 

 

 

 

 

Sorting data should not be an overbearing task. If you are looking for an efficient way to sort data, the PowerShell Sort-Object cmdlet is here to help!

In this tutorial, you will learn how to use the PowerShell Sort-Object cmdlet to sort data, be it numbers, strings, or objects.

Scrap the constant eyeballing through your data and sort them efficiently in PowerShell!

Prerequisites

Ensure you have a machine with PowerShell 5.0 or later installed for this tutorial to follow along with the hands-on demonstrations. This tutorial uses Windows 10 with PowerShell 7 installed.

Sorting Data with the PowerShell Sort-Object cmdlet

Depending on your requirements, you can sort data based on one or more properties in many ways. The Sort-Object cmdlet allows you to sort data, for example, in ascending or descending order to ease analyzing and working with structured information.

The basic syntax of the Sort-Object cmdlet is as follows where:

  • <Object-to-Sort> – Refers to collecting data to sort, such as an array, a list, or other data types.
  • <-Parameter> – An optional parameter to specify the sorting criteria that allows you to customize how the sorting is performed.
<Object-to-Sort>|Sort-Object <-Parameter>

To see how you can sort data in ascending and descending order:

1. Open PowerShell and run the below command, which does not provide output but defines a list of random integer numbers in the $numbers variable.

$numbers = 4, 2, 3, 1, 5

💡 Note that in PowerShell, you are not just working with numbers and strings but objects since PowerShell is an object-oriented language and shell.

2. Next, execute the following commands to sort (Sort-Objects) and display (Write-Output) the numbers defined in the $numbers variable.

$sortedNumbers = $numbers | Sort-Object
Write-Output $sortedNumbers

Without appending parameters, the output displays the numbers in ascending order.

Sorting data in ascending order

3. Now, run the same commands, but this time, append the -Descending parameter to sort and display the numbers in descending order.

$sortedNumbers = $numbers | Sort-Object -Descending
Write-Output $sortedNumbers

The output similar to the one below indicates the numbers have been sorted in descending order.

Sorting numbers in descending order
Sorting numbers in descending order

Sorting Data by Unique Values

Sorting data in ascending and descending order is one thing. But there may be instances where you need to sort data based on unique values. In this context, “unique” refers to distinct or non-repeated values within a dataset.

To sort data by unique values:

Run the following commands to perform the following:

  • Define a list of integer numbers (with duplicates included) in the $numbers variable.
  • Sort the numbers by -Unique values in -Descending order and store the result in the $sortedNumbers variable.

When sorting by unique values, you arrange the data so that each value appears only once in the sorted result, eliminating duplicates.

These commands do not provide output, but you will verify the sorted data in the following step.

$numbers = 4, 2, 3, 3, 1, 5, 2
$sortedNumbers = $numbers | Sort-Object -Unique -Descending

Now, run the Write-Output command below to output the contents of the $sortedNumbers variable to verify the result.

Write-Output $sortedNumbers

Below, all unique values are sorted in descending order, and duplicate values have been eliminated.

As you can see, sorting by unique values enhances data analysis efficiency and eliminates redundant information when dealing with large datasets.

powershell sort-object -Sorting data by unique values
Sorting data by unique values

Sorting Data by Strings

So far, you have seen how to sort numeric values. But what if you are working with strings? Worry not. The Sort-Object cmdlet lets you arrange string data in a specific order based on sorting criteria.

In this context, a string refers to a single character or a sequence of characters, such as words, phrases, or other textual data. In PowerShell, strings are represented by enclosing the text within quotation marks, either single (') or double (").

Execute the following commands to sort an array of strings in ascending (alphabetical) order by default.

Sorting strings in PowerShell provides flexibility in organizing textual data in a desired order, allowing efficient data manipulation and analysis.

# Define an array of strings
$strings = "a", "b", "c" 
# Sort the strings in ascending order by default (no parameters)
$sortedStrings = $strings | Sort-Object
# Display the sorted strings
Write-Output $sortedStrings
Sorting strings in alphabetical order
Sorting strings in alphabetical order

Now, run the same commands, but sort them in -Descending order instead.

# Define an array of strings
$strings = "a", "b", "c" 
# Sort the strings in descending order
$sortedStrings = $strings | Sort-Object -Descending
# Display the sorted strings
Write-Output $sortedStrings

This time you will see the output in the reverse order, as shown below.

Sorting strings in the reverse order
Sorting strings in the reverse order

Sorting Data by Properties

No doubt sorting string comes in handy. But typically, you should be more specific when sorting data. In addition to sorting strings, why not sort objects based on their properties?

When working with PowerShell objects, each object typically possesses one or more properties you can use for sorting. These properties allow you to define your sorting criteria tailored to your needs.

Execute the following commands to retrieve a list of all running processes (Get-Process) in your system and sort them by CPU utilization. The -Descending parameter displays the result with the most resource-intensive processes listed first.

# Retrieve a collection of all running processes
$processes = Get-Process

# Sort the processes based on CPU usage in descending order
$sortedProcesses = $processes | Sort-Object -Property CPU -Descending

# Select and display the Name and CPU properties of each process
$sortedProcesses | Select-Object Name, CPU
Sorting data by properties
Sorting data by properties

Sorting Hash Tables

Sorting objects by properties is a game-changer when working with data analysis. But what about organizing data in key-value pairs like hash tables?

The Sort-Object cmdlet lets you sort hash tables to enhance data presentation and simplifies information retrieval.

Run the following code to convert a hash table into an array of key-value pairs and sort the hash table by its keys.

# Create a hash table with three key-value pairs
$hashTable = @{
    "C" = "Charlie"
    "A" = "Alpha"
    "B" = "Bravo"
}

# Sort the hash table by keys and store the sorted result in $sortedHashTable
$sortedHashTable = $hashTable.GetEnumerator() | Sort-Object -Property Name

# Iterate through each entry in the sorted hash table
foreach ($entry in $sortedHashTable) {
    # Output the key-value pair
    Write-Output "$($entry.Name): $($entry.Value)"
}

Since keys sort the hash table, the output will resemble the following, where you can observe the output organizes and displays key-value pairs in a specific order.

This sorting method ensures better data presentation and makes retrieving information from the hash table easier.

Sorting hash tables
Sorting hash tables

Conclusion

Throughout this tutorial, you have explored how to sort unique values, strings, numbers, processes, and even hash tables with the Sort-Object cmdlet. Data sorting is one task that lets you pave the way to a more insightful data analysis, and with the PowerShell Sort-Object cmdlet, you are on the right track.

Armed with this newfound knowledge, you can now ensure your data is organized meaningfully and confidently showcase it to others.

Sorting is just one of the many valuable capabilities of PowerShell and its cmdlets. Why not expand your skills by learning about other cmdlets? Perhaps create program logs with Tee-Object or measure object sizes with Measure-Object?

Hate ads? Want to support the writer? Get many of our tutorials packaged as an ATA Guidebook.

Explore ATA Guidebooks

Looks like you're offline!