PowerShell-Technique: Randomizing

Created April 3, 2023

PowerShell-Technique: Randomizing

PowerShell is a powerful tool for automating tasks and managing systems, and one of its useful features is its ability to generate random values. In this post, we'll take a closer look at the Get-Random cmdlet and explore some of its lesser-known features.

To generate a random number between two values using Get-Random, you can use the -Minimum and -Maximum parameters. For example, to generate a random number between 1 and 10, you can run the following command:

Get-Random -Minimum 1 -Maximum 10

But did you know that you can also use the -Count parameter to generate multiple random values at once? For example, the following command generates three random numbers between 1 and 10 and stores them in an array:

Get-Random -Minimum 1 -Maximum 10 -Count 3

You can also pipe values to the Get-Random cmdlet, including strings, PSObjects, and other data types. The resulting output will depend on the input type, and there may be some typecasting involved. For example:

    Test = "test"
    Test2 = 4
}),3 | get-random

In addition to these features, Get-Random also includes a -Shuffle parameter that can be used to randomize the order of an input collection. While it may not always have a practical use case, it can be a fun way to mix things up.

The results are based on the input type, but it's important to be aware that typecasting can occur with certain input types.

Input Type Output Type
SByte Double
Byte Double
Int16 Double
UInt16 Double
Int32 Int32
UInt32 Double
Int64 Int64
UInt64 Double
Double Double
Single Double
Get-Help online reference

Perhaps this was no new information for you, but it demonstrates the value of reading the help page for even the most familiar cmdlets, as there may be useful features or parameters that you were not aware of before.

Thats all for now.

If you have any thoughts or feedback on this topic, feel free to share them with me on Twitter at Christian Ritter.

Best regards,