Converting VBScript's Rnd Function

Definition: Returns a random number.


Although it doesn’t require a lot of code to generate a random number in VBScript, the code that is required is a bit cryptic, to say the least. In Windows PowerShell the process is much easier: all you need to do is create an instance of the System.Random class and then call the Next method, passing this method the first and last numbers in the series. For example, these two commands create an instance of System.Random and then store a random number between 1 and 100 in the variable $b

$a = new-object random
$b = $,100)

When you run this command and then echo back the value of $b you should get something like the following:


And, of course, the next time you run the command you should get something different.

To generate a random integer (not necessarily an integer falling between a specified starting and ending number) just call the Next method without supplying any additional parameters:

$b = $

Return to the VBScript to Windows PowerShell home page