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:
1 2 3 4 5 |
$myFavFruits= @("Banana","Orange","Apple","Mango") $myFavFruits = $myFavFruits + "Guva" #Display the list of furits Write-Host ""; $myFavFruits | sort |
We can also sort based on our requirement by using “ascending” or “descending” cmdlet.
1 2 3 4 5 |
$myFavFruits= @("Banana","Orange","Apple","Mango") $myFavFruits = $myFavFruits + "Guva" #Display the list of furits Write-Host ""; $myFavFruits | sort -descending |
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:
1 2 3 4 5 6 |
$myFavFruits= @("Banana","Orange","Apple","Mango") $myFavFruits = $myFavFruits + "Guva" #Display the list of furits Write-Host ""; Write-Host "Top 3 fruits"; $myFavFruits | Sort-Object | select -First 3 |
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:
1 |
$myFavFruits | Sort-Object | Status , DisplayName |
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.
1 |
$myFavFruits | sort -Unique |
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.
1 |
$myFavFruits | sort Startname -Unique -CaseSensitive |
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:
1 |
$myFavFruits = $null |
Leave A Comment