Wednesday, 13 December 2017

Generate Random Numbers within a Range using PowerShell

We may required to generate a random number to set ID or in some cases to set temporary password. In PowerShell we can easily generate random numbers using Get-Random cmdlet and we can also use this cmdlet to select objects randomly from a collection of objects.

Summary:

Example 1: Get a random number

If you run Get-Random command without parameters or input it will returns a 32-bit unsigned random integer between 0 (zero) and Int32.MaxValue (2,147,483,647).
PS C:\> Get-Random
475917250

Example 2: Get a random number between given range

To set the range, we need to use the parameters -Minimum and -Maximum. The below command return a random number between 1 and 100.
PS C:\> Get-Random -Minimum 1 -Maximum 100
27

Example 3: Get a random number from array of numbers

Instead of generating random number from a given range we can also get a random number from our own list of numbers.
PS C:\> Get-Random -InputObject 1, 2, 4, 8, 12, 16,20,24
16
We can also get more than one random numbers by setting the parameter -Count.
PS C:\> Get-Random -InputObject 1, 2, 4, 8, 12, 16,20,24 -Count 3
2
8
20

Example 4: Get a character from random ASCII code

The ASCII code of upper-case alphabetical characters starts from 65 (A) and ends in 90 (Z), and lower-case chars starts from 97 (a) and ends in 122 (z), so we can get random number within this range and convert it to alphabetical character.
$code = Get-Random -Minimum 65 -Maximum 90
$random_char = [char]$code
Write-Host $random_char -ForegroundColor 'Yellow'

Example 5: Generate random password from ASCII code

In some situation we may required to generate random password from ASCII values with standard format, we can easily achieve this by getting random chars within the range of ASCII code.
$randomPassword = ""
1..5 | ForEach { 
$code = Get-Random -Minimum 65 -Maximum 122
$randomPassword = $randomPassword + [char]$code
}
Write-Host $randomPassword -ForegroundColor 'Yellow'

Advertisements
Advertisements

No comments:

Post a Comment