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

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()
PSH [D:\foo]:
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(), where the first number is part of the range, but the second is above the max value you wish to compute, as shown   here:
PSH [D:\foo]: $rand = New-Object system.randomPSH [D:\foo]: $,11) # gets random number between 1 and 10
PSH [D:\foo]: $,17)
# gets random number between 5 and 16

Thanks to a couple of readers who spotted that the second parameter was exclusive.


Ry Jones said...

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

Unknown said...

check this out
$r.Next(0,1) never generate one it is always 0 so the upper bound is not inclusive.

Unknown said...

You are both correct. The upper bound is actually exclusive. So to create a number between 1 and ten, you'd use next(1,11). Some may regard this as a bug of the API. For others it's a feature.

Thomas Lee said...

Well spotted. The second parameter is exclusive. To create a random number between 0 and 1, you'd type $,2).

Thanks for spotting this.

leftler said...

@tim, It is most definitely not a feature.

If you have an array it is indexed 0 to length-1. Using Next you can just call "Next(0, myArray.Length)" and always get a valid index.