社内SEの話

日々起きたことの記録用

PowerShell - Randomly swap array values

↓プログラミングで副業を考えたらこちら↓

There are not many cases that occur, but since it was in another language, I tried implementing it with PowerShell.

The command differs depending on the version of PowerShell, so check the actual version.

Before Code 7.0

$arr = @("aa","bb","cc","dd","ee")

for($i= 0;$i -ne $arr.Length;$i++){

$_rdm = get-random -Maximum ($arr.Length-1) -Minimum 0

$_tmp = $arr[$i]

$arr[$i] = $arr[$_rdm]

$arr[$_rdm] = $_tmp

}

Get-Random

learn.microsoft.com

Get-Random is a default integer type unless it is specified with a decimal point. return.

-Maximum

specifies the number of arrays, but the number returned is the index as it is, so the number of elements in the array is -1

-Minimum The

minimum value is 0

Another example

$arr = @("aa","bb", "cc","dd","ee")

$rdm = get-random -Maximum $arr.Length -Minimum 0 -Count $arr.Length

foreach($_r in $rdm){

$_tmp = $arr[$rdm .indexof($_r)]

$arr[$rdm.indexof($_r)] = $arr[$_r]

$arr[$_r] = $_tmp

}

get random in array. Use the -Count parameter to get an array.

Use Foreach instead of For.

To get the index during Foreach, you can get the index with Array.IndexOf($Item).

From Code 7.1

$arr = $arr | Get-Random -Shuffle

From version 7.1 onwards you can use the -Shuffle parameter to directly shuffle the array.

learn.microsoft.com

Finally,

it is better not to use PowerShell6 or earlier versions.

If you use PowerShell7 or later versions, a variety of tools are available, so you can easily write code in PowerShell.