Powershell Windows 表单列表框选择验证

Powershell Windows Form listbox selection validation

我创建了一个 powershell 脚本,使用 windows 包含列表框的表单到 运行 cmd 命令(有助于消除用户错误并稍微加快处理速度)。我 运行 遇到的唯一问题是该命令仍将尝试 运行 即使在我填充的其中一个表单上未选择项目。这可能导致脚本根本无法 运行,或者它可能导致下载大量数据(脚本从服务器拉取日志文件,列表框有助于缩小要拉取的数据)。有没有办法为列表框创建错误检查,在继续之前基本上会说 "hey, you didn't select anything!" ? 谢谢!

编辑(第一个列表框的例子):

$form = New-Object System.Windows.Forms.Form 
$form.Text = "Select a production environment"
$form.Size = New-Object System.Drawing.Size(190,250) 
$form.StartPosition = "CenterScreen"

$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Point(10,180)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "OK"
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$form.AcceptButton = $OKButton
$form.Controls.Add($OKButton)

$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Point(85,180)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = "Cancel"
$CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$form.CancelButton = $CancelButton
$form.Controls.Add($CancelButton)

$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(10,20) 
$label.Size = New-Object System.Drawing.Size(280,20) 
$label.Text = "Please select a production environment:"
$form.Controls.Add($label) 

$listBox = New-Object System.Windows.Forms.ListBox 
$listBox.Location = New-Object System.Drawing.Point(10,40) 
$listBox.Size = New-Object System.Drawing.Size(150,20) 
$listBox.Height = 140

[void] $listBox.Items.Add("server1")
[void] $listBox.Items.Add("server2")
[void] $listBox.Items.Add("server3")


$form.Controls.Add($listBox) 

$form.Topmost = $True

$result = $form.ShowDialog()

if ($result -eq [System.Windows.Forms.DialogResult]::OK)
{
    $Prod = $listBox.SelectedItem
    $Prod
}

可能有一种方法可以使用 Windows Forms 方法执行这种验证,但这使用 PowerShell。


Do..UntilDo..While 循环中执行 $result = $form.ShowDialog() 并继续显示对话,直到用户至少选择了一项并按下 OK - 或者用户退出对话 - 否则,显示警告并再次显示对话。
这是相关的 PowerShell 代码:

do
{
    $result = $form.ShowDialog()

    if ($ListBox.SelectedIndices.Count -lt 1 -and $result -eq [System.Windows.Forms.DialogResult]::OK)
    {
        Write-Warning 'Nothing was selected, please select a server.'
    }
}
until (($result -eq [System.Windows.Forms.DialogResult]::OK -and $listBox.SelectedIndices.Count -ge 1) -or $result -ne [System.Windows.Forms.DialogResult]::OK)

当然,你可以把Write-Warning换成任何你想要的,比如消息框。


PS:您可以使用 AddRange 方法将项目数组添加到 $listBox 集合,如下所示:[void] $listBox.Items.AddRange(@("server1", "server2", "server3"))