Creating Random Numbers

by Feb 13, 2009

Ever wanted to create an electronic dice (or needed random numbers for other purposes)? With PowerShell, simply instantiate a Random object and call its Next() method:

$random = new-object random
$random.Next(1,6)

This gives you a new random number between 1 and 6 each time you call Next(). Hint: just change the parameters to auto-generate your next lottery numbers… or use this to create lists of random passwords. The next line generates ten passwords of eight characters length:

1..10 | % {  1..8 | % {$pwd = ''} { $pwd+= [char]$random.next(33,95) } {$pwd.toLower() } }

Note that PowerShell V2 includes a new Cmdlet called Get-Random.