Saturday, January 20, 2007

Random Numbers in PowerShell

With PowerShell, you can leverage the .NET Framework's System.Random class to create random numbers. To create a random numbers you must first create a new random number object, then the object's methods to generate a random number as follows:

$rand = New-Object  System.Random
$rand.next()

If you want  a random  number  between 0 and  1, you can use the .NextDouble method which woule look like this:

PSH [D:\foo]: $rand = New-Object system.random
PSH [D:\foo]: $rand.nextdouble()
0.370553521611986
PSH [D:\foo]:
$rand.nextdouble()
0.561135980561905

If you want to create random numbers that  are between two other numbers (e.g. a random number  between 1 and 10, or between  4 and 16), you can specify a bottom and top range in a call to .NEXT() as shown   here:

PSH [D:\foo]: $rand = New-Object system.random
PSH [D:\foo]: $rand.next(1,10)
7
PSH [D:\foo]: $rand.next(4,16)
14

 

1 comments:

Ry Jones said...

This isn't quite correct. To generate a number between 4 and 16, you need to use (4,17)