Generating random numbers in PowerShell

When creating PowerShell scripts, very often we need to generate random numbers to use in several scenarios. In Today’s post, we are going a couple of examples how to use it.

Solution


The easiest way to use random is typing random and a random number will be generated, however, we have some flexibility to get random numbers based on our requirements.

We can use the Get-Random cmdlet and provide the maximum and minimum values to define the range to return a number within that defined boundaries, as depicted in the image below.

Get-Random -Maximum 50 -Minimum 30

image

A good example to use random is when using Start-Sleep and we want to add some random delays. In the example below, we create a random number between 5 and 15, and we add 6 and start a delay (in that example of 16 seconds).

image