我之前问过这个问题,但没有结果,所以我再次询问。我确定并进行了搜索,同时还尝试使用自己的代码(反复试验)来在发布之前弄清楚它。我正在尝试创建某种信息亭或小程序,当从列表中选择一个项目然后单击按钮时,将允许执行操作。这可以是安装应用程序、启动控制台或运行脚本之类的任何内容。我有另一个使用与功能相关的按钮的按钮,但它变得挤满了一堆按钮,所以我认为列表会更干净。
Add-type -AssemblyName system.windows.forms
$formobject = [System.Windows.forms.form]
$OfficeMenuForm=New-object $formobject
$OfficeMenuForm.clientsize= '750,500' #set the height and width
$OfficeMenuForm.text ='Office Installation Menu'
$OfficeMenuForm.backcolor='White'
$DefaultFont='Verdana,10'
$OfficeMenuForm.Font=$DefaultFont
#Build form
$labelobject = [System.Windows.Forms.Label]
$ComboBoxObject=[System.Windows.Forms.ComboBox]
$LabelTitle=New-Object $labelobject
$LabelTitle.Text='Make a selection from the dropdown menu then click the Install button'
$LabelTitle.AutoSize=$true
$LabelTitle.Location=New-Object System.Drawing.Point(10,10)
$BtnObject= [System.Windows.Forms.Button]
$BtnInstall=New-Object $BtnObject
$BtnInstall.Text='Install'
$BtnInstall.AutoSize=$true
$BtnInstall.font='Verdana,10'
$BtnInstall.Location=New-Object System.Drawing.Point(550,250)
$DDLOffice=New-Object $ComboBoxObject
$DDLOffice.Width='300'
$DDLOffice.Location=New-Object System.Drawing.Point(30,40)
#Add items to the dropdownlist
@('LTSC 2021 STD x64','LTSC 2021 STD+Project+Visio Std x64','LTSC 2021+Project
STD')|ForEach-Object {[void]$DDLOffice.Items.Add($_)}
#Select default value
$DDLOffice.SelectedIndex=0
#lable to confirm selection
$LabelObject1=[System.Windows.Forms.Label]
$LabelOutPut=New-Object $LabelObject1
$LabelOutPut.Text="You selected: $Choice"
$LabelOutPut.AutoSize=$true
$LabelOutPut.location=new-object System.Drawing.Point (100,400)
#catch selection
$DDLOffice.add_SelectedIndexChanged({
$choice=$DDLOffice.SelectedItem
$LabelOutPut.Text="You selected: $Choice"
})
Function install{
if ($DDLOffice.SelectedIndex='2'){
start-process notepad.exe
}
}
$BtnInstall.Add_Click({Install})
#create an array to accept all the controls you want to appear on the form
$OfficeMenuForm.Controls.AddRange(@($LabelTitle,$BtnInstall,$DDLOffice,$LabelOutPut))
$OfficeMenuForm.showdialog() #displays the form
$OfficeMenuForm.dispose() #cleans up form
您的代码的问题是在您的
=
函数中使用 -eq
(赋值)而不是
install
(相等比较运算符),所以简单地说:
function install {
if ($DDLOffice.SelectedIndex -eq 2) {
Start-Process notepad.exe
}
}
可以解决您的问题,在这种情况下您也可以使用
switch
:
function install {
switch ($DDLOffice.SelectedIndex) {
0 { Write-Host "do thing for index 0" }
1 { Write-Host "do thing for index 1" }
2 { Start-Process notepad }
}
}