PowerShell: How to Randomize Elements in an Array


You can use the following syntax in PowerShell to randomize the elements in an array:

$random_array = $my_array | Sort-Object {Get-Random}

This particular example randomizes the elements in the array named $my_array and saves the results in a new array named $random_array.

This syntax works by using the Get-Random cmdlet to generate a massive random integer value, then by using the Sort-Object cmdlet to sort the values of the original array based on these massive random integer values.

The following example shows how to use this syntax in practice.

Example: How to Randomize Elements in Array in PowerShell

We can use the following syntax to create an array named $my_array in PowerShell that contains the numbers 1 through 10:

$my_array = 1..10

We can then use the following syntax to randomize the values in this array and save the results in a new array named $random_array:

$random_array = $my_array | Sort-Object {Get-Random}

The following screenshot shows how to use this syntax in practice:

PowerShell randomize array

From the output we can see that the original values have been randomized and saved in a new array named $random_array.

We can see that the values in this random array are in the following order:

  • 8, 7, 2, 6, 1, 5, 3, 10, 9, 4

This new array contains all of the values from the original array, but they are now sorted in a random order.

It’s worth noting that each time you run this code the elements will be sorted in a new random order.

Note: You can find the complete documentation for the Get-Random cmdlet in PowerShell here.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: Generate Random Number Between Range
PowerShell: How to Generate Random Password
PowerShell: How to Find Duplicate Values in Array

Leave a Reply