Generating Random Numbers in a Range Using PowerShell

Generating Random Numbers in a Range Using PowerShell

Most you of you should be familiar with the Get-Random cmdlet in PowerShell, but if not, Get-Random is a one-line cmdlet that will automatically generate random numbers. Run by itself, it will generate any random number, as shown in the following example:

A good use of running the default command is to auto-generate number passwords that end-users can use as a temporary password when they forget their own.

While there are many uses for the default action of the Get-Random cmdlet, say you have a reason to limit the range of the numbered output. As a long-time conference and event person, one example that comes to my mind is for selecting winners in Expo drawings. I've seen many times where vendors will pull up on a booth computer to supply drawing results, but if PowerShell is installed on the computer no Internet connection is needed, just use Get-Random. By assigning numbers or tickets to booth visitors you can set your number range to select from, and using additional options with the Get-Random cmdlet, produce the desired results. That's my example, but I'm sure you can come up with a bunch on your own.

To set the range, use the Minimum and Maximum options as shown:

In this example, I've set the maximum number to 51 and the minimum number to 1.  Why not 50 as the maximum number? Because of the way the PowerShell cmdlet generates random numbers you must always set the Maximum value to one number beyond your desired limt to fit within the accepted range. Also, as shown in the example, I set the Minimum to 1 because, unless I did, the number 0 (zero) would also be a valid option.

Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.