Sort Object - PowerShell


Overview

Sort-Object is a PowerShell command used to sort objects in a collection based on specified properties. It arranges objects in ascending or descending order, making it useful for organizing and filtering data. This command is commonly employed in data management, reporting, and object manipulation scenarios.

Syntax

Sort-Object [-Property] <Property> [-Descending] [-CaseSensitive] [-Unique] [[-PassThru] | [-InputObject] <object>]

Options/Flags

  • -Property: Specifies the property to sort by. Can be used multiple times to sort on multiple properties.
  • -Descending: Sorts in descending order instead of ascending.
  • -CaseSensitive: Performs case-sensitive sorting for text properties. Default is case-insensitive.
  • -Unique: Outputs only unique objects based on the specified property.
  • -PassThru: Outputs the sorted objects. When absent, only the number of sorted objects is returned.
  • -InputObject: Accepts an object or array of objects to be sorted.

Examples

Simple Sort by Name:

Get-ChildItem | Sort-Object Name

Descending Sort by LastWriteTime:

Get-ChildItem | Sort-Object -Property LastWriteTime -Descending

Multiple Property Sort:

Get-Process | Sort-Object PriorityClass, Name

Case-Sensitive Sorting:

Get-File | Sort-Object -Property Name -CaseSensitive

Unique Objects by Size:

Get-File | Sort-Object -Property Length | Select-Object -Unique

Common Issues

  • Case-Insensitive Sorting by Default: Remember to use -CaseSensitive for accurate text sorting.
  • Sorting Numerical Properties: Specify the -Descending flag explicitly for descending order since numbers are sorted ascending by default.
  • Passing Objects: Ensure the correct object is passed to -InputObject for customized sorting.

Integration

Pipeline Processing: Sort-Object can be used with other commands in pipelines to refine data further.
Scripting: This command is often used in scripts to automate sorting tasks and generate organized reports.

  • Where-Object: Filters objects based on conditions.
  • Select-Object: Selects specific properties from objects.
  • Group-Object: Groups objects based on common properties.
  • Sort-ByProperty: Similar functionality, but limited to sorting on a single property.