Powershell Windows窗体列表框选择验证

时间:2018-08-24 16:33:58

标签: winforms powershell listbox error-checking

我使用Windows窗体(包含用于运行cmd命令的列表框)创建了Powershell脚本(有助于消除用户错误并加快处理速度)。我遇到的唯一问题是,即使未在我填充的表单之一上选择任何项目,该命令仍将尝试运行。这可能导致脚本根本无法运行,或者可能导致下载大量数据(脚本从服务器提取日志文件,列表框有助于缩小要提取的数据)。有没有一种方法可以为列表框创建错误检查,该错误检查基本上会显示“嘿,您没有选择任何内容!”在继续之前? 谢谢!

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

$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
}

1 个答案:

答案 0 :(得分:0)

也许可以使用Windows Forms方法执行这种验证,但是要使用PowerShell。


$result = $form.ShowDialog()Do..Until循环中执行Do..While,并继续显示对话框,直到用户选择了至少一项,然后按下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"))