Collections and Randomization


Randomize Collections in PowerShell

Randomizing a collection is useful in a variety of situations and in most languages it is fairly straight forward.

For example

  • Python

    my_list = range(1,20)
    random.shuffle(my_list)
    
  • PHP

    $numbers = range(1, 20);
    shuffle($numbers);
    

In PowerShell this works a bit differently.

Before 7.1

PS> @(1,2,3) | Sort-Object {Get-Random}
3
1
2

PS> "abc".ToCharArray() | Sort-Object {Get-Random}
a
c
b

Well, how does that work?

Sort-Object allows us to sort the incoming collection based on a script block. In most cases we reference the $_ input object in this script block, but we must not do that. As Get-Random returns a large random number it is good enough for most cases.

7.1 and later

Starting with PowerShell 7.1 Get-Random introduced the new parameter -Shuffle, making this operation more straight forward.

PS> @(1,2,3) | Get-Random -Shuffle
2
1
3

PS> "abc".ToCharArray() | Get-Random -Shuffle
c
a
b

Other Use Cases

  • Omitting the -Shuffle parameter changes the output to just one randomly selected element

    This can be useful for selecting one item, like a server, at random

    PS> @(1,2,3) | Get-Random
    3
    
  • You can specify how many random elements you want to receive from your collection with the -Count parameter

    PS> @(1,2,3) | Get-Random -Count 1
    3
    
    PS> @(1,2,3) | Get-Random -Count 2
    1
    3
    

Info

You cannot receive more elements than the original collection contains

PS> @(1,2,3) | Get-Random -Count 5
1
3
2

Have fun randomizing your collections in PowerShell!

See also