Sorting a hash table
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]
}