Get-Random

Exploring the PowerShell Cmdlet: Get-Random

Welcome back to Wahmans PowerShell blog! Today we’re diving into a very handy cmdlet that lets you bring randomness into your scripts: Get-Random.

According to Microsoft, Get-Random "Gets a random number, or selects objects randomly from a collection." It’s an incredibly flexible tool for a variety of use cases, from generating random data for testing to implementing simple game logic or load balancing tasks.

Let’s walk through four examples that explore Get-Random in increasing order of complexity.

Example 1: Generate a Simple Random Number

This is the most basic usage. Running Get-Random with no arguments returns a random 32-bit integer.

# Generate any random number
ggRandomNumber = Get-Random
Write-Host "Random number: $ggRandomNumber"

Example 2: Get a Random Number Within a Specific Range

You can specify a maximum or a range using parameters.

# Get a number between 1 and 100
$number = Get-Random -Minimum 1 -Maximum 101
Write-Host "Random number from 1 to 100: $number"

Example 3: Select a Random Item from a List

This is great for when you have a collection of items and want to randomly pick one, such as for a prize draw, team assignment, or snack picker!

# List of fruits
$fruits = @("Apple", "Banana", "Orange", "Grape", "Peach")
$randomFruit = Get-Random -InputObject $fruits
Write-Host "Selected fruit: $randomFruit"

Example 4: Shuffle an Array (Advanced)

You can use Get-Random along with array manipulation to shuffle the order of items — useful for randomized testing or simple games.

# Shuffle an array of numbers
$numbers = 1..10
$shuffled = $numbers | Sort-Object { Get-Random }
Write-Host "Shuffled numbers: $($shuffled -join ', ')"

As you can see, Get-Random is a powerful and flexible tool. It is simple enough for beginners, but can be leveraged creatively for complex scripting scenarios.

Happy scripting, and I will see you in the next post!

Leave a Reply

Your email address will not be published. Required fields are marked *