Get Random - PowerShell
Overview
Get-Random generates a random number or an array of random numbers within a specified range. It’s useful for tasks like generating unique identifiers, shuffling data, or simulating random events.
Syntax
Get-Random [-Min] <int> [-Max] <int> [-Count] <int>
Options/Flags
| Option | Description | Default |
|—|—|—|
| -Min | Minimum value for the random number(s) | 0 |
| -Max | Maximum value for the random number(s) | 2,147,483,647 |
| -Count | Number of random numbers to generate | 1 |
Examples
Example 1: Generate a single random integer within a range:
Get-Random -Min 1 -Max 100
Example 2: Generate an array of 5 random integers within a range:
Get-Random -Min 1 -Max 50 -Count 5
Common Issues
- Invalid range: If
-Min
is greater than-Max
, an exception will be thrown. - Invalid count: If
-Count
is a non-positive integer, an exception will be thrown.
Integration
Example: Generate a random password of a specific length:
$chars = ((1..9) + (65..90) + (97..122) | ForEach-Object { $_ -as [char] })
$pwd = (Get-Random -Min 0 -Max ($chars.Count - 1) -Count 10) | ForEach-Object { $chars[$_] }