Sorting Array Values Using PowerShell

Rohan Timalsina Jul 07, 2022
Sorting Array Values Using PowerShell

An array is a data structure used as a collection of multiple items. The items can be the same or different types.

The array items are stored in the index number in ascending integer order starting from zero. In this tutorial, you will learn to sort array values in PowerShell.

Use Sort-Object Cmdlet for Sorting Array Values in PowerShell

The Sort-Object cmdlet sorts objects based on the property values. PowerShell uses the default sort properties of the first input object when no properties are specified in the command.

You can pipe the objects to Sort-Object for sorting them in ascending or descending order.

You can create an array using the array sub-expression operator @(). The items are placed in the @() parentheses.

The following command creates an array $vehicles containing five items.

$vehicles=@("Cars", "Trucks", "Bus", "Train", "Jeep")

Next, call the array variable to view items.

Command:

$vehicles

Output:

Cars
Trucks
Bus
Train
Jeep

In the following example, sort the array of objects in ascending order.

Command:

$vehicles | Sort-Object

Output:

Bus
Cars
Jeep
Train
Trucks

Use the -Descending parameter to sort the objects in descending order.

Command:

$vehicles | Sort-Object -Descending

Output:

Trucks
Train
Jeep
Cars
Bus

PowerShell is known for its cmdlets and their aliases. The Sort-Object has built-in alias sort.

As shown below, you can also pipe the objects sorted to sort.

Command:

$vehicles | sort

Output:

Bus
Cars
Jeep
Train
Trucks

In this way, you can easily sort array values using PowerShell.

Rohan Timalsina avatar Rohan Timalsina avatar

Rohan is a learner, problem solver, and web developer. He loves to write and share his understanding.

LinkedIn Website

Related Article - PowerShell Array