Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randomize a List of Elements in a Powershell Array

I'm looking to take an array of elements and return a randomized version of the array in a function.

For example:

function Randomize-List
{
   Param(
     [int[]]$InputList
   )
   ...code...
   return 10,7,2,6,5,3,1,9,8,4
}

$a = 1..10
Write-Output (Randomize-List -InputList $a)
10
7
2
...

You get the idea. No idea of how to approach this, I'm new to Powershell, coming from a Python background.

like image 494
Michael Scott Avatar asked Jan 27 '15 20:01

Michael Scott


People also ask

How do you use Random in PowerShell?

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.

How do you generate a random number in PowerShell?

In order to randomly choose from a set of items, we are going to make use of the Get-Random cmdlet. Get-Random will pick a random number or a random object from a collection of objects.By default, Get-Random will pick a random number between 0 and the maximum 32-bit integer value (2,147,483,647).

How do you create an array in PowerShell?

To create and initialize an array, assign multiple values to a variable. The values stored in the array are delimited with a comma and separated from the variable name by the assignment operator ( = ). The comma can also be used to initialize a single item array by placing the comma before the single item.

How do I add values to an array in PowerShell?

To add value to the array, you need to create a new copy of the array and add value to it. To do so, you simply need to use += operator. For example, you have an existing array as given below. To add value “Hello” to the array, we will use += sign.


1 Answers

You can use Get-Random to do this in PowerShell.

function Randomize-List
{
   Param(
     [array]$InputList
   )

   return $InputList | Get-Random -Count $InputList.Count;
}

$a = 1..10
Write-Output (Randomize-List -InputList $a)
like image 172
MatthewG Avatar answered Oct 05 '22 10:10

MatthewG