Get-Random powershell command

Get-Random | Taking on PowerShell one cmdlet at a time | Weekly Blog

Share this post:

This is a part of an on-going blog series written by Adam Gordon. Each week, Adam will walk you through a PowerShell command, showing you when and how to use each one. This week, Adam covers Get-Random.

When to use Get-Random

The Get-Random cmdlet gets a randomly selected number. If you submit a collection of objects to Get-Random, it gets one or more randomly selected objects from the collection.

Without parameters or input, a Get-Random command returns a randomly selected 32-bit unsigned integer between 0 (zero) and Int32.MaxValue (0x7FFFFFFF, 2,147,483,647).

You can use the parameters of Get-Random to specify a seed number, minimum and maximum values, and the number of objects returned from a submitted collection.

 

How to use Get-Random

Get a random integer:

Get-Random

Get-Random gets a random integer between 0 (zero) and Int32.MaxValue.

Get-Random powershell command

 

Get a random integer between -100 and 99:

Get-Random -Minimum -100 -Maximum 100

Get-Random powershell command

 

Get a random floating-point number:

Get-Random -Minimum 10.81 -Maximum 22.52

Get-Random powershell command

 

Get a random integer from an array:

1, 2, 3, 5, 8, 13, 18, 29 | Get-Random

Get-Random powershell command

 

Get several random integers from an array:

 1, 2, 3, 5, 8, 13, 29, 45, 20212 | Get-Random -Count 3

Get-Random powershell command

 

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 order.

The value of the –Count parameter is the MaxValue static property of integers.

Get-Random powershell command

 

Get random files: 

$Files = Get-ChildItem -Path C:\cygwin64 -Recurse
$Sample = $Files | Get-Random -Count 50
$Sample

These commands get a randomly selected sample of 50 files from the C: drive of the local computer, and then display them on the screen as the output of the $Sample variable.

Get-Random powershell command

 

Roll fair dice:

1..1200 | ForEach-Object {
    1..10 | Get-Random
} | Group-Object | Select-Object Name,Count

This example rolls a fair die 1200 times and counts the outcomes.

The first command, For-EachObject repeats the call to Get-Random from the piped in numbers (1-10). The results are grouped by their value with Group-Object and formatted as a table with Select-Object.

Get-Random powershell command

Get-Random powershell command

Need PowerShell training? Check out ITProTV’s PowerShell online IT training courses.

Leave a Reply

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