Winform:更新组合框时出现问题



我正在使用Powershell开发一个Windows窗体,该窗体将在打印服务器上查询所有已安装的打印机(函数:FetchPrinters(。我添加了一个按钮来运行FetchPrinters功能。

Function:
$Global:PrintServer = ""
function FetchPrinters {
$printerTxtFileLocation = 'C:TempPrinterList.csv'
$outputBox.text = "Fetching list of printers on $Global:PrintServer"
# $Global:PrintServer = $Global:DropDownBox1.SelectedItem.ToString()
Get-Printer -ComputerName "$Global:PrintServer" | Select-Object -ExpandProperty Name | Sort-Object -CaseSensitive | Out-File -Force -Encoding utf8 -FilePath "$printerTxtFileLocation"
$PrinterList = Get-Content -Path "$printerTxtFileLocation" -Encoding UTF8 -Force
foreach ($Printer in $PrinterList) {
$DropDownBox2.ResetText()
[void] $DropDownBox2.Items.Add($Printer)
}
}

在Dropdownbox1中,将有一个站点(位置(列表,当选择该列表时,将确定要查询的打印服务器。

$DropDownBox1 = New-Object System.Windows.Forms.ComboBox 
$DropDownBox1.Text = "Select Site Name"
$DropDownBox1.Size = New-Object System.Drawing.Size(190, 20)
$DropDownBox1.Location = New-Object System.Drawing.Point(20, 20)
$Sites = @(
'Site 1',
'Site 2',
'Site 3',
'Site 4',
'Site 5',
'Site 6'
'Site 7'
)

ForEach ($Site in $Sites) {
$DropDownBox1.Items.Add($Site) | Out-Null
}

$Global:DropDownBox1_SelectedIndexChanged = {
Switch ($DropDownBox1.Text) {
'Site 1' { $Global:PrintServer = "\Printserver1" }
'Site 2' { $PrintServer = "\Printserver2" }
'Site 3' { $PrintServer = "\Printserver3" }
'Site 4' { $PrintServer = "\Printserver3" }
'Site 5' { $PrintServer = "\Printserver4" }
'Site 6' { $PrintServer = "\Printserver5" }
'Site 7' { $PrintServer = "\Printserver6" }
}
}
$DropDownBox1.add_SelectedIndexChanged($Global:DropDownBox1_SelectedIndexChanged)
$Form.Controls.Add($DropDownBox1)

在下拉框2中,将有可用于安装的打印机列表

$DropDownBox2 = New-Object System.Windows.Forms.ComboBox
$DropDownBox2.Text = "Select the Printer to install"
$DropDownBox2.Location = New-Object System.Drawing.Size(20, 60) 
$DropDownBox2.Size = New-Object System.Drawing.Size(180, 20) 
$DropDownBox2.DropDownHeight = 200

$DropDownBox2.add_SelectedIndexChanged({ })
$Form.Controls.Add($DropDownBox2)

按原样,一切都很好,我可以在Drowndownbox1中选择一个站点,点击"获取打印机"按钮,Dropdownbox2显示该站点可用的打印机。

我遇到的问题是,当我尝试选择另一个网站(以相同的形式(,并点击"获取打印机"按钮时,$Printers变量会保留它看起来像的旧数据,因此Dropdownbox2包含上一个查询和当前查询中的打印机。

理想情况下,每当我选择一个网站,点击提取打印机,下拉框2只包含该网站的信息。

我尝试过使用Clear Variable cmdlet,但它似乎没有起到作用,但也有可能我做错了什么,而且没有正确思考。

任何帮助都将不胜感激。

看起来要添加:

$dropdownbox2.Items.Clear() 

到我的功能做我需要的。我本可以发誓我试过这个,但可能语法错误。

最新更新