从Powershell列表框中删除选定的项目

时间:2018-12-28 10:20:17

标签: powershell

单击按钮后,我想从列表中删除选定的项目。 这是我的GUI生成的代码,带有删除逻辑(请参阅$ Button1.Add_Click方法-第31行)

Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()

 $Form = New-Object system.Windows.Forms.Form
 $Form.ClientSize = '400,400'
 $Form.text = "Form"
 $Form.TopMost = $false

 $ListBox1 = New-Object system.Windows.Forms.ListBox
 $ListBox1.text = "listBox"
 $ListBox1.width = 156
 $ListBox1.height = 274
@('Ronaldo', 'Pele', 'Maradona', 'Zidan', 'Pepe') | ForEach-Object {[void] 
$ListBox1.Items.Add($_)}
$ListBox1.location = New-Object System.Drawing.Point(12, 23)
$ListBox1.SelectionMode = "MultiExtended"

$Button1 = New-Object system.Windows.Forms.Button
$Button1.text = "button"
$Button1.width = 60
$Button1.height = 30
$Button1.location = New-Object System.Drawing.Point(197, 16)
$Button1.Font = 'Microsoft Sans Serif,10'

$Form.controls.AddRange(@($ListBox1, $Button1))

$Button1.Add_Click( {
    $items = $ListBox1.SelectedItems
    ForEach ($item in $items) {
        $ListBox1.Items.Remove($item)
    }
})

[void]$Form.ShowDialog()

由于某种原因,它仅删除$ items中的第一项。其他被忽略。 为什么?

1 个答案:

答案 0 :(得分:0)

如该错误消息所示,您无法在foreach循环的中间更改数组:

List that this enumerator is bound to has been modified.
An enumerator can only be used if the list does not change.

您可以使用while循环并在每次删除后再次检索SelectedItems[0]引用数组的第一个元素:

while($ListBox1.SelectedItems) {
        $ListBox1.Items.Remove($ListBox1.SelectedItems[0])
}