How to Generate Random Number in PowerShell

Introduction

In this blog post, we will show you different ways to generate random number in PowerShell.

Solution

Using Get-Random Cmdlet

We can use Get-Random cmdlet to generate random number. The following example will generate random number x where 3 <= x < 17. In other words, the lower bound is 3 inclusive and the upper bound is 17 exclusive. So, we will never get 17 as the result.


Get-Random -Minimum 3 -Maximum 17

Using Random Class from .NET Framework

PowerShell allows us to utilize .NET Framework, thus we can use Random class to generate random number. Similar to previous example, the following example will generate random number with 3 as inclusive lower bound and 17 as exclusive upper bound.


$rand = New-Object System.Random
$rand.Next(3, 17)

Conclusion

In conclusion, to generate random number in PowerShell we can use Get-Random cmdlet and Random class from .NET Framework.