我有一个脚本,用户可以从下拉列表中选择选项。但如果用户没有选择任何内容,我就会收到错误。即使用户未输入值,如何设置返回的默认值。
这是脚本
########################
# Edit This item to change the DropDown Values
[array]$DropDownArray = "c", "d", "share"
# This Function Returns the Selected Value and Closes the Form
function Return-DropDown {
$script:Choice = $DropDown.SelectedItem.ToString()
$Form.Close()
}
function selectShare{
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
$Form = New-Object System.Windows.Forms.Form
$Form.width = 300
$Form.height = 150
$Form.Text = ”DropDown”
$DropDown = new-object System.Windows.Forms.ComboBox
$DropDown.Location = new-object System.Drawing.Size(100,10)
$DropDown.Size = new-object System.Drawing.Size(130,30)
ForEach ($Item in $DropDownArray) {
[void] $DropDown.Items.Add($Item)
}
$Form.Controls.Add($DropDown)
$DropDownLabel = new-object System.Windows.Forms.Label
$DropDownLabel.Location = new-object System.Drawing.Size(10,10)
$DropDownLabel.size = new-object System.Drawing.Size(100,40)
$DropDownLabel.Text = "Select shared folder to deploy SEP"
$Form.Controls.Add($DropDownLabel)
$Button = new-object System.Windows.Forms.Button
$Button.Location = new-object System.Drawing.Size(100,50)
$Button.Size = new-object System.Drawing.Size(100,20)
$Button.Text = "Select an Item"
$Button.Add_Click({Return-DropDown})
$form.Controls.Add($Button)
$Form.Add_Shown({$Form.Activate()})
[void] $Form.ShowDialog()
return $script:choice
}
$share = selectShare
write-host $share
如果用户不从下拉列表中选择,则会出现错误
You cannot call a method on a null-valued expression.
At D:\Script\comp.ps1:10 char:2
+ $script:Choice = $DropDown.SelectedItem.ToString()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
为什么不直接做:
$DropDown.SelectedItem = $DropDown.Items[0]
在你展示表格之前?或者将其设置为 = 无论您的默认项目是什么。
Edit:或者更好的是,设置一个值检查函数并在单击“确定”时调用该函数以确保所有字段都具有有效值。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)