获取随机并从数组中删除

时间:2015-03-27 23:27:25

标签: arrays powershell random

想要创建一系列任务,然后在分配它们时将它们从数组中删除。

到目前为止,这适用于获取随机任务:

$Tasks = "a", "b", "c", "d"
$RandomTask = Get-Random $Tasks

但是当我尝试删除它时,我会收到错误:

$Tasks = "a", "b", "c", "d"
$RandomTask = Get-Random $Tasks

#Something will assign the task here

$Tasks.Remove("$RandomTask")

如何从阵列中删除随机选择的字符串?我一直这样:

Exception calling "Remove" with "1" argument(s): "Collection was of a fixed size."

3 个答案:

答案 0 :(得分:2)

创建后,您无法添加或删除具有普通数组的项目,因为它们具有固定长度。要做你想做的事,你需要使用System.Collections中更强大的ArrayList class

$Tasks = New-Object System.Collections.ArrayList
$Tasks.AddRange(("a", "b", "c", "d"))

现在,您可以按原样调用$Tasks.Remove方法:

PS > $Tasks = New-Object System.Collections.ArrayList
PS > $Tasks.AddRange(("a", "b", "c", "d"))
PS > $Tasks
a
b
c
d
PS > $Tasks.Remove("b")
PS > $Tasks
a
c
d
PS > 

答案 1 :(得分:1)

阵列具有固定大小,无法修改。您需要使用ArrayList,列表或其他类似的集合才能使用Remove()RemoveAt()Add()等。示例:

$tasks = [System.Collections.ArrayList]("a", "b", "c", "d")

#Loop through every item in arraylist
1..$tasks.Count | ForEach-Object {
    #Get random task
    $randomtask = Get-Random $tasks.ToArray()

    Write-Host "Random task is: $randomtask"

    #Remove random task
    $tasks.Remove($randomtask)

    #Display remaining tasks
    $tasks
}
Random task is: c
a
b
d
Random task is: d
a
b
Random task is: b
a
Random task is: a

我建议使用通用List,因为ArrayLists是非类型化的并且已弃用。要为字符串对象使用通用列表,需要进行一些修改:

$tasks = [System.Collections.Generic.List[String]]("a", "b", "c", "d")

#Loop through every item in arraylist
1..$tasks.Count | ForEach-Object {
    #Get random task
    $randomtask = Get-Random $tasks.ToArray()

    Write-Host "Random task is: $randomtask"

    #Remove random task (List's Remove() method returns a bool
    $tasks.Remove($randomtask) | Out-Null

    #Display remaining tasks
    $tasks
}

如果您的对象属于不同的类,则可以尝试List[object]

答案 2 :(得分:0)

一个选项是随机化任务,并将它们加载到queue,然后使用.dequeue()方法返回任务并自动将其从队列中删除:

$tasklist = 'a','b','c','d'

$taskqueue = [collections.queue]($tasks | Get-Random -Count $tasks.count)

For ( $i=1; $i -le $tasklist.Count; $i++ )
{
$Task = $taskqueue.Dequeue()
Write-Host "Current task: $Task"
Write-Host "Remaining tasks: $taskqueue`n"
}

Current task: c
Remaining tasks: b d a

Current task: b
Remaining tasks: d a

Current task: d
Remaining tasks: a

Current task: a
Remaining tasks: