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.
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.
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).
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With