Musings on code and life

PowerShell Random Number Generator

I needed a small script that would print all the numbers within a given range randomly for giveaways at a user group so I threw this PowerShell script together.


#REF https://gist.github.com/pwhe23/0758a860aba3abaf20ca

Add-Type -AssemblyName 'System.Windows.Forms'
Add-Type -AssemblyName 'Microsoft.VisualBasic'

$maximum = [int ][Microsoft.VisualBasic.Interaction]:: InputBox("Enter Maximum (inclusive)", "Max" , "5" )
$popup = $true

function Main () {
    if ($Host .Name -eq "Windows Powershell ISE Host") {
        Clear-Host
    }
    PrintList(GetRandom ($maximum))
}

function GetRandom ([int ] $max , [ int] $seed = 0) {
   
    if ($seed -eq 0) {
        $ticks = [DateTime ]::Now. Ticks.ToString()
        $ticks = ([regex ]::Matches($ticks ,'.', 'RightToLeft') | ForEach { $_.value}) -join ''
        $seed = $ticks. Substring(0, 9)
    }

    Get-Random -SetSeed $seed | Out-Null

    $list = New-Object System.Collections.Generic.List[System.String]
    while ($list .Count -lt $max) {
        $rand = Get-Random -Minimum 1 -Maximum ( $max+1 )
        if (-not $list. Contains($rand)) {
            $list.Add( $rand)
        }
    }

    return $list
}

function PrintList ($list) {
    $index = 0
    while ($index -lt $list.Count) {
        $msg = ($index+ 1). ToString().PadLeft( 2) + ": " + $list [$index]
        Write-Host $msg

        if ($popup -eq $true) {
            $continue = [System.Windows.Forms.MessageBox ]::Show($list [$index], "Continue?" , 4 )
            if ($continue -eq "No") {
                $popup = $false
                #return
            }
        }       

        $index += 1
    }
}

Main