我正在使用Windows窗体编写PowerShell脚本,该脚本创建了一个GUI供用户输入数据,每当用户在字段中输入不正确的信息时,它都会使用状态栏来告诉用户他们输入的数据不正确。
我在辅助函数中具有此功能,并且使用if语句确定用户输入的数据是否不正确。如果是这样,脚本应该返回到开头,因为该表单始终处于打开状态,直到用户单击右上角的“ X”按钮或单击我创建的“关闭”按钮。
不幸的是,当用户输入不正确的信息并单击“提交”按钮时,它将引发错误消息框,指出“应用程序中的组件发生了未处理的异常。如果单击继续,则应用程序将忽略此信息。错误并尝试继续。”
我尝试对指定的消息和SilentlyContinue使用Break,Throw和Write-Error。所有方法都抛出相同的错误框。有什么办法可以抑制此错误框?
编辑:这是我的脚本中的错误处理:
if(-Not ($myVar.Text.ToString()) {
$sBar.Text = "Invalid input. Please try again."
Write-Error "Invalid input error" -ErrorAction Stop #Can be replaced with Continue or SilentlyContinue, gives same error. Throw, Exit, and Break also give the same error of unhandled exception.
}
$myVar
是Windows窗体中的文本字段,而$sBar
是状态栏。
以下是错误弹出窗口的样子:
答案 0 :(得分:1)
因此,PowerShell错误正确返回。捕获它的Windows窗体并产生允许用户继续前进的错误处理框。看看这个article by Adam Bertram。他讨论了如何在Powershell Windows窗体中正确显示错误。
“您必须弄清楚如何向脚本用户指示发生了错误。”
$statusBar = New-Object -TypeName System.Windows.Forms.StatusBar
$statusBar.Text = ‘Message status bar’
$Form.Controls.Add($statusBar)
$Form.ShowDialog()
单击按钮或提交内容时,请执行以下操作:
$button.add_Click({
try
{
<strong>Get-Content</strong> -Path C:\File.txt
}
catch
{
$statusBar.Text = $_.Exception.Message
}
})