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.
[Object]$Random = New-Object System.Random
Lets checkout the $Random object:
$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()
Now with this object you can now create random numbers very simple:
Create a random double number:
$Random.NextDouble()
Create a random int number:
$Random.Next()
Create a random number between 1 or 10:
$Random.Next(1,11)
Create a random number between 12 or 25:
$Random.Next(12,26)
Create a random number 1 or 0:
$Random.Next(0,2)