如何抑制 PowerShell .net GUI 错误

How to suppress PowerShell .net GUI errors

我正在使用 Windows 表单编写 PowerShell 脚本,为用户输入数据创建 GUI,每当用户在字段中输入不正确的信息时,它都会使用状态栏告诉用户输入的数据不正确。

我在一个辅助函数中有这个,一个if语句用来判断用户输入的数据是否不正确。如果是,脚本应该回到开头,因为表单始终打开,直到用户点击右上角的 "X" 按钮,或者点击我制作的 "Close" 按钮。

不幸的是,当用户输入不正确的信息并点击 "Submit" 按钮时,它会抛出一个错误消息框,上面写着 "Unhandled exception has occurred in a component in your application. If you click Continue, the application will ignore this error and attempt to continue."

我尝试对指定消息使用 Break、Throw 和 Write-Error 以及 SilentlyContinue。所有方法都抛出相同的错误框。有什么办法可以抑制这个错误框吗?

编辑: 这是我的脚本中的错误处理:

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 是状态栏。

错误弹出窗口如下所示:

因此您的 PowerShell 错误正在正确返回。它是 Windows 表单捕获它并生成允许用户继续的错误处理框。看看这个 article by Adam Bertram。他谈到了如何在 powershell windows 表单中正确显示错误。

"You must figure out how to indicate to the user of your script that an error has occurred."

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