By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

Random numbers with PowerShell and .NET

How to generate random numbers in PowerShell scripting

Created: 2014-01-02 01:55

You can use the .NET Framework's System.Random class to generate random numbers in a PowerShell script. To do this, you will first need to create a new object for creating random numbers, then use the objects methods to create a random number.

The following will output a nonnegative random integer number between 1 and 10:

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

Note that the upper bound is not inclusive, so we need to make it 11 to make it possible to generate the number 10.

Floating-point numbers between 0.0 and 1.0

To generate a number between 0 and 1, you can use the NextDouble method, which will generate a number like:

0,124251448693545