Friday, August 15, 2008


The current Sort-Object cmdlet in PowerShell lacks "random" functionality.
Here is a small function that allows youto sort randomly:

function sort-random {
    process {
        [array]$x = $x + $_
    end {
        $x | sort-object {(new-object Random).next()}


1..100 | Sort-Random
- or -
Get-Process | Sort-Random


Stephen Mills said...

Here's another easy way to sort randomly. It uses a GUID to sort randomly. GUIDs aren't trully random, but they are very close and don't repeat.
1..100 | sort {[System.Guid]::NewGuid()}

Or, if you can't remember how to get the guid, then create a function:

function New-GUID {[System.Guid]::NewGuid()}

Then use the function to sort:
1..100 | sort { New-GUID }


Anonymous said...

V2 supports this through Get-Random!

1,2,3 | Get-Random -Count 3

Lee Holmes [MSFT]
Windows PowerShell Development
Microsoft Corporation

Jakob Bindslet said...

Yes, but we are still waiting for version 2.0 ;-)

vaibhav said...

Hi Jakob,

I need a help on sorting user defined numbers.
Say user entered 10 numbers , then the output should be in sorted order.