Dreaming In PowerShell V2 : Lottery Numbers with Get-Random

Tobias Weltner writes a blog called Dreaming In PowerShell, and he recently posted a way to get a list of unique lottery numbers with PowerShell.  Dreaming In PowerShell is a cool blog, and the post is interesting, but it makes an assertion that’s no longer true in V2.  He uses System.Random to create the random numbers because he asserts that there isn’t a cmdlet to Get random numbers.  Get-Random is a V2 cmdlet that can not only give you random numbers, but can give you unique random numbers within a range

My CTP3 version is on the left, Tobias’ V1 version is on the right:

My CTP3 Version Tobias’ V1 version:
function Get-RandomNumbers($minimum = 1, $maximum = 49, $number = 20)
{
#.Synopsis
#   Gets a series of unique random numbers
#.Description
#   Gets a series of unique random numbers between a minimum and a maximum
#.Parameter number
#   The number of unique numbers needed
#.Parameter minimum
#   The lowest number the random numbers could contain
#.Parameter maximum
#   The highest number the random numbers could contain
#.Link
#   Get-Random
#.Example
#   Get-RandomNumbers 10 1 100
    $minimum..$maximum | 
        Get-Random -Count $number |
        Sort-Object
}
function Get-RandomNumbers($minimum = 1, $maximum = 49, $number = 20) {
    $random = New-Object System.Random
    $result = @()
    do {
        $randomnumber = $random.Next($minimum,$maximum)
        if ($result -notcontains $randomnumber) {
            $result += $randomnumber
        }
    } while ($result.count -lt $number)
    $result = $result | Sort-Object
    $result
}

The core function is a lot shorter (3 lines in CTP3 to 10 lines in V1), but my CTP3 version has inline help.  This means not only can I easily Get unique random numbers, I can also get help about getting unique random numbers.

While I’m showing Get-Random with a bunch of numbers, you can easily use the same thing to select from a list of words.  Check out this pipeline that gives you 5 random verbs to explore

Get-Command -type Cmdlet |
        Group-Object Verb | 
        Foreach-Object { $_.Name } |
        Get-Random -count 5

Isn’t CTP3 Fun?

Hope this Helps,

James Brundage [MSFT]