PowerShell Get-Random: Generate Random Numbers and Pick Items

PowerShell Get-Random: Generate Random Numbers and Pick Items

PowerShell Tips Editor 3 min read
PowerShell Get-Random: Generate Random Numbers and Pick Items

Whether you are generating test data, sampling a large dataset, randomizing deployment order to spread load, or shuffling a list of servers for round-robin tasks, PowerShell Get-Random handles it with a clean one-liner. This post covers generating numbers in ranges, picking items from arrays, shuffling collections, controlling reproducibility with seeds, and when to use cryptographic randomness instead.

Quick Answer / TL;DR

Get-Random -Minimum 1 -Maximum 100 for a number in range. $array | Get-Random for a single random item. $array | Get-Random -Count $array.Count to shuffle. Get-Random -SetSeed 42 for reproducible sequences.

Generate a Random Integer

With no parameters, Get-Random returns a random non-negative integer up to [int32]::MaxValue (2,147,483,647). The result changes on every call and is suitable for testing, sampling, and non-security uses.

# Random integer (0 to Int32.MaxValue)
Get-Random

# Random with -Count generates multiple values
1..5 | ForEach-Object { Get-Random }
1847392615

Set Min and Max Range

-Minimum is inclusive; -Maximum is exclusive. So -Minimum 1 -Maximum 101 generates numbers from 1 to 100 (not 101). This matches PowerShell’s range convention and .NET’s Random.Next(minValue, maxValue) behavior.

# Number from 1 to 100 (inclusive)
Get-Random -Minimum 1 -Maximum 101

# Simulated dice roll (1-6)
Get-Random -Minimum 1 -Maximum 7

# Random delay between 5 and 15 seconds for staggered script starts
$delay = Get-Random -Minimum 5 -Maximum 16
Write-Host "Starting in $delay seconds..."
Start-Sleep -Seconds $delay

Pick Random Items from an Array

Piping an array to Get-Random picks one element at random. Add -Count N to select N elements without replacement (no element picked twice). This is ideal for sampling a subset from a large collection.

# Pick a single random item from array
$servers = @('web01','web02','web03','web04','web05')
$target  = $servers | Get-Random
Write-Host "Selected: $target"

# Pick 3 random servers without replacement
$sample = $servers | Get-Random -Count 3
Write-Host "Sample: $($sample -join ', ')"

# Select a random AD user for testing
Get-ADUser -Filter * | Get-Random | Select-Object Name, SamAccountName
Selected: web03
Sample: web01, web04, web02

Shuffle an Array

Use -Count equal to the array length to shuffle all elements into a random order. This returns a new array with all elements rearranged randomly — the original array is unchanged.

# Shuffle entire array
$tasks = @('TaskA','TaskB','TaskC','TaskD','TaskE')
$shuffled = $tasks | Get-Random -Count $tasks.Count
$shuffled

# Randomize deployment order across servers
$deployOrder = Get-ADComputer -Filter * | Get-Random -Count 999999
$deployOrder | ForEach-Object {
    Write-Host "Deploying to: $($_.Name)"
    # ... deploy code ...
}

Seeding for Reproducible Results

The -SetSeed parameter initializes the random number generator with a specific value. Given the same seed, Get-Random produces the same sequence of numbers every time. This is invaluable for debugging randomized tests or generating reproducible test data sets.

# Same seed always produces same sequence
Get-Random -SetSeed 42 -Minimum 1 -Maximum 100   # Always returns same value
Get-Random -SetSeed 42 -Minimum 1 -Maximum 100   # Same value again

# Generate reproducible random test data
$seed = 12345
$testData = 1..10 | ForEach-Object {
    Get-Random -SetSeed ($seed + $_) -Minimum 100 -Maximum 999
}
Write-Host "Reproducible data: $($testData -join ', ')"

When Not to Use Get-Random (Security)

Get-Random uses .NET’s System.Random, which is a pseudo-random number generator (PRNG) — not cryptographically secure. For security-sensitive uses like generating passwords, tokens, salt values, or cryptographic keys, use [System.Security.Cryptography.RandomNumberGenerator] instead.

# DO NOT use Get-Random for security-sensitive values
# $token = Get-Random  ← predictable and not secure!

# USE: cryptographic randomness for security contexts
function Get-CryptoRandom {
    param([int]$ByteCount = 16)
    $bytes = [byte[]]::new($ByteCount)
    [System.Security.Cryptography.RandomNumberGenerator]::Fill($bytes)
    return [Convert]::ToBase64String($bytes)
}

# Generate a cryptographically secure 32-byte token
$secureToken = Get-CryptoRandom -ByteCount 32
Write-Host "Secure token: $secureToken"

# Generate a random password character set (non-crypto Get-Random is fine for this)
$chars    = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%'
$password = -join ($chars.ToCharArray() | Get-Random -Count 16)

Common Errors and Fixes

  • Get-Random without -Count returns single item from array. $array | Get-Random returns exactly one element — a scalar, not an array. If you then call .Count on the result, you get the count of the single item’s characters (for a string) or 1. Add -Count 1 and wrap in @() if you always need an array.
  • Same seed always produces same sequence — intended behavior. Setting -SetSeed is deterministic by design. If your script is producing the same “random” values on every run, check whether a static seed is being set somewhere in the code. Remove -SetSeed for non-reproducible randomness in production scripts.

Related Cmdlets / See Also

Wrapping Up

Get-Random handles the common randomization cases in automation: number ranges, array sampling, shuffling, and reproducible test data with seeds. Remember that -Maximum is exclusive, -Count picks without replacement, and the built-in PRNG is not cryptographically secure. For tokens, passwords, and crypto keys, always reach for System.Security.Cryptography.RandomNumberGenerator.

Send-Item -To