Random Numbers in Powershell

Powershell Header

In one of my last scripts I needed random numbers in Powershell. Now this Blog post should show you how you can generate random numbers in Powershell very simple.

To create random numbers in Powershell you can use the .NET Framework class “System.Random”. First you have to create a new object.

[powershell]
[Object]$Random = New-Object System.Random
[/powershell]

Lets checkout the $Random object:

[powershell]
$Random | Get-Member
TypeName: System.Random

Name MemberType Definition
—- ———- ———-
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
Next Method int Next(), int Next(int minValue, int maxValue), int Next(int maxValue)
NextBytes Method System.Void NextBytes(byte[] buffer)
NextDouble Method double NextDouble()
ToString Method string ToString()
[/powershell]

Now with this object you can now create random numbers very simple:

Create a random double number:
[powershell]
$Random.NextDouble()
[/powershell]

Create a random int number:
[powershell]
$Random.Next()
[/powershell]

Create a random number between 1 or 10:
[powershell]
$Random.Next(1,11)
[/powershell]

Create a random number between 12 or 25:
[powershell]
$Random.Next(12,26)
[/powershell]

Create a random number 1 or 0:
[powershell]
$Random.Next(0,2)
[/powershell]