PowerShell Sort and Select
Sorting and selecting means putting pipeline items in order and then choosing which ones to keep. Sort-Object orders the items, and Select-Object picks from the ordered result.
Sort words into order
Split a sentence into words first. Sort-Object then puts those words in A to Z order.
("pear apple fig banana" -split " " | Sort-Object) -join ", "Sort numbers in reverse
Add -Descending to flip the order. The largest number now comes first.
(1..5 | Sort-Object -Descending) -join ", "Take the first and last items
Select-Object -First takes items from the start. Select-Object -Last takes items from the end.
(1..10 | Select-Object -First 3) -join ", "
(1..10 | Select-Object -Last 2) -join ", "Pull out one property value
Select-Object -ExpandProperty prints plain values. Here it prints the length of each word.
"pear apple fig" -split " " | Select-Object -ExpandProperty LengthExample
$words = "pear apple fig banana" -split " "
$sorted = $words | Sort-Object
($sorted | Select-Object -First 2) -join ", "Key points
- Sort-Object: Sort-Object puts pipeline items in order.
- Ascending order: Items sort smallest to largest, or A to Z, unless you ask otherwise.
- Descending order: The -Descending switch reverses the order.
- First items: Select-Object -First takes a set number of items from the start.
- Last items: Select-Object -Last takes a set number of items from the end.
- ExpandProperty: Select-Object -ExpandProperty prints the values of one property instead of objects.
In this example, the words are split and sorted into A to Z order. Select-Object -First 2 then keeps only the first two words, and they are joined into one line.
Note
Sorting never changes the original values. It only changes the order they come out in.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which command gives the first 3 items of the range 1 to 10?