Home/PowerShell/PowerShell – Sorting in Array

PowerShell – Sorting in Array

Sort array:

It’s very easy of arranging the elements of an array in a order with PowerShell. Just we need to do is pipe the output of an array to the Sort-Object cmdlet: The default sort order is ascending : the numbers range from small to large. To perform a descending sort requires utilizing the Descending switch.

Example:

We can also sort based on our requirement by using “ascending” or “descending” cmdlet.

Select top elements in Array:

In this case, the sorted output is piped to the Select-Object cmdlet to select the top five elements/values as shown like below.

Example:

READ  PowerShell's Variables

You can sort on any object property like name, date… on single properties or  multiple properties. It can be used by separate them with commas:

Remove Duplicate Entries in Array:

Another way to use the Sort-Object cmdlet is to sort on a property using the -Unique parameter to eliminate duplicates and return a set of unique values.

Sort by Case Sensitive:

The another important point to know about Sort-Object is that sorting is case insensitive by default. Case-sensitive sorting isn’t used too often, but let we see simple demonstrate how it works in case the need arises. If you want to force the sort to be case sensitive, you need to include the Case-sensitive parameter as like below.

Delete arrays and elements:

Even though most of the array operations in PowerShell are relatively easy to accomplish, no convincing solution exists for removing specific elements or deleting complete arrays. The easiest way to get rid of an entire array is to assign the variable $null:

Leave A Comment