Michael Scott
Michael Scott

Reputation: 589

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.

Upvotes: 16

Views: 14522

Answers (1)

MatthewG
MatthewG

Reputation: 9293

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)

Upvotes: 25

Related Questions