我正在创建一个 PowerShell 函数,用于使用 GUI 在 AD 中搜索用户。该函数将 ShowDialog() 一个 Windows 表单供用户进行搜索,然后当用户单击“确定”时,该表单将关闭,并且该函数将返回一个包含他们选择的 AD 用户的 ArrayList。
一切正常,直到表格关闭。表单关闭后,我的 ArrayList 突然计数为 0,而不是包含他们选择的 AD 用户。
我不明白为什么 ArrayList ($alRetrievedSelection) 被清空。我实际上只有一行代码可以修改这个 ArrayList。其他一切都只是出于我自己的调试目的的写警告。
#This function returns an arraylist that contains the items selected by the user
function Retrieve-DataGridSelection{...}
#Fake sample data
$array = "Item 1","Item 2","Item 3","Item 4"
$arraylist = New-Object System.Collections.ArrayList(,$array)
#Create the basic form
$frmWindow = New-Object System.Windows.Forms.Form
#Create the OK button
$btnOK = New-Object System.Windows.Forms.Button
$btnOK.Add_Click({
$alRetrievedSelection = Retrieve-DataGridSelection -dgDataGridView $datagrid
#This warning always shows the correct Count
Write-Warning("Received from Retrieve-DataGridSelection: " + $alRetrievedSelection.Count)
})
$frmWindow.Controls.Add($btnOK)
#Create the datagrid where users will select rows
$datagrid = New-object System.Windows.Forms.DataGridView
$datagrid.DataSource = $arraylist
$frmWindow.Controls.Add($datagrid)
#Give focus to the form
$frmWindow.Add_Shown({$frmWindow.Activate()})
#Display the form on the screen
$frmWindow.ShowDialog()
#This warning keeps telling me the Count is 0 when it should not be
Write-Warning("After the form closes: " + $alRetrievedSelection.Count)