Coding Ref

How to sort in PowerShell

How to sort in PowerShell

To sort items in PowerShell, you can use the Sort-Object cmdlet.

This cmdlet allows you to sort objects based on the values of their properties, and to control the order in which the objects are sorted (ascending or descending).

Examples

Example 1: Sort an array in ascending order

Here is an example of how to create an array and sort it in PowerShell:

# Create the array
$myArray = 1, 3, 5, 2, 4

# Sort the array in ascending order
$sortedArray = $myArray | Sort-Object

# Output the sorted array
$sortedArray

In this example, the Sort-Object cmdlet is used to sort the items in the $myArray array in ascending order. The sorted array is then stored in the $sortedArray variable, and the sorted array is output to the screen.

Example 2: Sort an array in descending order

The Sort-Object cmdlet can also be used to sort the items in the array in descending order. To do this, you can use the -Descending parameter.

For example, the following code sorts the array in descending order:

# Create the array
$myArray = 1, 3, 5, 2, 4

# Sort the array in descending order
$sortedArray = $myArray | Sort-Object -Descending

# Output the sorted array
$sortedArray
By default, the `Sort-Object` cmdlet sorts objects in ascending order. You can use the `-Descending` parameter to sort objects in descending order instead.

Example 3: Sort an object by a specific property

Here is an example of how to use the Sort-Object cmdlet to sort objects by a specific property:

$sortedObjects = Get-Process | Sort-Object -Property CPU

In this example, the Sort-Object cmdlet is used to sort the objects returned by the Get-Process cmdlet by the value of their CPU property. The sorted objects are then stored in the $sortedObjects variable.

Example 4: Sort an object by multiple properties

You can also use the Sort-Object cmdlet to sort objects by multiple properties.

For example, the following code sorts the objects first by their CPU property, and then by their Memory property:

$sortedObjects = Get-Process | Sort-Object -Property CPU, Memory

Conclusion

To sort items in PowerShell, you can use the Sort-Object cmdlet.

This cmdlet allows you to sort objects based on the values of their properties, and to control the order in which the objects are sorted (ascending or descending).

You'll also like

Related tutorials curated for you

    How to rename a computer in PowerShell

    What is Write-Host in PowerShell?

    How to write multiple-line comments in PowerShell

    Dictionaries in PowerShell

    How to print output in PowerShell

    What is read-host in PowerShell?

    How to check for equality in PowerShell

    Everything about certificates in PowerShell

    What is null in PowerShell?

    How to sort and filter data in PowerShell

    How to find the Windows version from the PowerShell command line

    How to add a user to a group in PowerShell