Taking on PowerShell one cmdlet at a time

Share this post: This is part of an ongoing blog series by Adam Gordon. Adam will show you how to use each PowerShell command each week. Adam will be covering Get-Random this week.

When to use Get Random
The Get-Random cmdlet randomly selects a number. You can submit a collection to Get-Random and it will randomly select one or more objects from that collection.
A Get-Random command returns an unsigned 32-bit integer randomly selected between 0 (zero), and Int32.MaxValue (0x7FFFFFFFF, 2,147.483,647).
You can specify a seed number and minimum and maximum values as well as the number of objects that will be returned from a submitted collection using the parameters of Get–Random.

How to use Get Random
Find a random integer
Get-Random
Get-Random returns a random integer between zero (zero) or Int32.MaxValue.

Find a random integer between 100 and 99:
Get-Random -Minimum -100 -Maximum 100

Get a random floating point number:
Get-Random -Minimum 10.81 -Maximum 22.52

Find a random integer in an array:
1, 2, 3, 5, 8, 13, 18, 29 | Get-Random

You can get several random integers from an array.
1, 2, 3, 5, 8, 13, 29, 45, 20212 | Get-Random -Count 3

Randomize an entire collection
1, 2, 3, 5, 8, 13, 0, 2654, 4433198 | Get-Random -Count ([int]::MaxValue)
This command returns the entire collection in random ordering.
The MaxValue static property is integers, and the value of the parameter -Count is its value.

Download random files:
$Files = Get-ChildItem -Path C:\cygwin64 -Recurse$Sample = $Files | Get-Random -Count 50$Sample
These commands will randomly select 50 files from the C drive of your local computer and display them on the screen using the $Sample variable.

Play fair:
1..1200 | ForEach-Object Get-Random | Group-Object | Select-Object Name,Count
This example rolls a fair dice 1200 times and counts its outcomes.
The first command, For–EachObject, repeats the call for Get-Random using the piped-in numbers (1-10). The results are grouped according to their value using Group-Object, and formatted as a table using Select-Object.

Do you need PowerShell training? ITProTV offers PowerShell online IT training courses.