16

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.

1 Answer 1

25

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)
2
  • 22
    You could also use $InputList | Sort-Object {Get-Random} [source]. Jan 27, 2015 at 20:24
  • 1
    Get-Random proves to be much faster than Sort-Object, especially for large input arrays. See related question. Also, PowerShell Core 7+ adds Get-Random parameter -Shuffle, so we can write $shuffledArray = Get-Random -InputObject $arrayToShuffle -Shuffle
    – zett42
    Feb 5, 2023 at 23:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.