In the previous tip we showed how Sort-Object can sort multiple properties, and how you can use hash tables to control sort direction individually per property. Hash tables can do a lot more, though.

For example, the hash table key “Expression” can be a script block, and this script block is then executed for each item that you want to sort. The result of the script block determines the sort order.

That’s why this line will rearrange the list of numbers each time in a different way:

1..10 | Sort-Object -Property @{Expression={ Get-Random }}  

In essence, this example uses the random result of Get-Random to randomly sort the list of numbers. This can be useful i.e. when you work on a password generator and would like to randomly distribute the characters your script calculated:

# compose password out of these
$Capitals = 2
$Numbers = 1
$lowerCase = 3
$Special = 1

# collect random chars from different lists in $chars
$chars = & {
    'ABCDEFGHKLMNPRSTUVWXYZ'.ToCharArray() | Get-Random -Count $Capitals
    '23456789'.ToCharArray() | Get-Random -Count $Numbers
    'abcdefghkmnprstuvwxyz'.ToCharArray() | Get-Random -Count $lowerCase
    '!§$%&?=#*+-'.ToCharArray() | Get-Random -Count $Special
} | # <- don't forget pipeline symbol!
# sort them randomly
Sort-Object -Property { Get-Random }

# convert chars to one string
$password =  -join $chars 

As you see in the practical example, Sort-Object also accepts a plain script block which represents the “Expression” key of a hash table. Both lines work identically (yet produce random results of course that differ):

1..10 | Sort-Object -Property @{Expression={ Get-Random }}
1..10 | Sort-Object -Property { Get-Random }

Twitter This Tip! ReTweet this Tip!