Search notes:

PowerShell cmdLet Sort-Object

sort-object sorts an array of objects based on a given property value, or in absence thereof, on a default sort property.
Duplicates can optionally be removed from the sorted output by using the -unique command option.
Using -top n or -bottom n only returns the first n objects from the head or last n object from the tail of the sorted result. (This is somewhat similar to using top n queries in SQL).

Sorting a hash table

In order to sort the key/value pairs in a hash table with sort-object, the hash table's method GetEnumerator() (See System.Collections.IEnumerable) needs to be used.
This is because a hash table is one object which is meaningless to be sorted.
The following example tries to demontrate how a hash table is used to count word occurences and than to display the number of occurences for each word in ascending order.
We need a hashtable ($words):
$words = @{}
Counting the words. Each new word creates a new key/value pair with the key being the word and the value being 0 (which is the default value for an integer).
The ++ operator increments the value of each word that is seen:
foreach ($word in 'two', 'four', 'one', 'four', 'four', 'three', 'four', 'three', 'two', 'three') {
   $words[$word]++
}
After the words have been counted, $words can be inspected with an arbitrary order of key(name)/value parirs:
$words

Name          Value
----          -----
one           1
three         3
two           2
four          4
sort-object is now used to sort the entries in the hash table according to their value:
$words.GetEnumerator() | sort-object -property value

Name          Value
----          -----
one           1
two           2
three         3
four          4

Sorting text on the nth word

The following example uses the -split operator to sort text on the second word:
'abcde one y',
'fg two w',
'hijk three z',
'lm four t',
'nop five x',
'qrstu six u' | sort-object {
   ($_ -split '\s+')[1]
}

See also

Powershell command noun: object

Index