0
0
PowerShellscripting~5 mins

Sort-Object for ordering in PowerShell

Choose your learning style9 modes available
Introduction

Sorting helps you organize data so it's easier to read and understand. Sort-Object arranges items in order, like sorting names alphabetically.

You have a list of files and want to see them by date from newest to oldest.
You want to organize a list of names alphabetically.
You need to sort numbers from smallest to largest.
You want to display processes sorted by memory usage.
You want to sort data before exporting it to a report.
Syntax
PowerShell
Sort-Object [-Property] <string[]> [-Descending] [-Unique] [-CaseSensitive] [-Culture <string>] [-Stable]

-Property specifies the property or value to sort by. If omitted, it sorts the objects themselves.

-Descending sorts from highest to lowest instead of lowest to highest.

Examples
Sorts running processes by CPU usage in ascending order.
PowerShell
Get-Process | Sort-Object -Property CPU
Sorts files by last modified date, newest first.
PowerShell
Get-ChildItem | Sort-Object -Property LastWriteTime -Descending
Sorts a list of strings alphabetically.
PowerShell
'apple','banana','cherry' | Sort-Object
Sorts numbers from largest to smallest.
PowerShell
5,3,9,1 | Sort-Object -Descending
Sample Program

This script creates a list of people with their ages. It sorts them by age from youngest to oldest and prints their names with ages.

PowerShell
$data = @(
    @{Name='John'; Age=30},
    @{Name='Anna'; Age=25},
    @{Name='Mike'; Age=35}
)

$data | Sort-Object -Property Age | ForEach-Object { "$($_.Name) is $($_.Age) years old" }
OutputSuccess
Important Notes

Sort-Object works well with both simple values and complex objects.

Use -Descending to reverse the order.

Sorting large data sets may take more time.

Summary

Sort-Object arranges data in order to make it easier to understand.

You can sort by any property or value.

Use -Descending to sort from highest to lowest.