Get-Random

Welcome back to Wahmans PowerShell blog! Today, we’re diving into an incredibly useful cmdlet in the PowerShell toolbox: Get-Random.

Overview: What is Get-Random?

According to Microsoft docs, Get-Random “gets a random number, or selects objects randomly from a collection.” This makes it a powerful and flexible cmdlet that can be used in a variety of scenarios such as automation, testing, and data manipulation.

Example 1: Get a Random Number (Beginner)

This is the most basic use of Get-Random—getting a random number.

Get-Random

This returns a non-negative integer less than [int]::MaxValue.

Example 2: Select a Random Item from an Array (Intermediate)

Let’s imagine you’re building a script that randomly assigns tasks to team members. Here’s how you could select a random person from a list:

$team = @("Alice", "Bob", "Charlie", "Diana")
$randomMember = Get-Random -InputObject $team
Write-Host "Today's lucky team member is: $randomMember"

Example 3: Generate a Random Number in a Range (Intermediate)

You can generate a number within a defined range using the -Minimum and -Maximum parameters:

Get-Random -Minimum 1 -Maximum 100

This returns an integer between 1 and 99. Note: the -Maximum value is exclusive.

Example 4: Shuffle a Collection (Advanced)

Want to shuffle a list of items or files? Here’s how to randomly reorder a collection:

$items = 1..10
$shuffled = $items | Sort-Object {Get-Random}
$shuffled

This uses Get-Random as a sort key to randomly reorder the items in the array from 1 to 10. A great trick for randomizing data!

In Conclusion

Get-Random is a versatile cmdlet that can help with everything from simple automation to complex scripting challenges. Whether you’re selecting a random item or simulating randomized test input, it’s a go-to part of the PowerShell scripting arsenal.

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 *