windowspowershellerror-handlingwindows-scripting

How to suppress PowerShell .net GUI errors


I'm writing a PowerShell script using Windows Forms that creates a GUI for users to input data, and whenever a user inputs information that is incorrect in a field, it uses a status bar to tell a user that the data they input is incorrect.

I have this in a helper function, and an if statement is used to determine if the data that the user inputs is incorrect. If it is, the script is supposed to go back to the beginning, as the form is always open until the user either hits the "X" button in the top right, or hits a "Close" button I made.

Unfortunately, when the user puts in incorrect information and hits the "Submit" button, it throws an error message box that says "Unhandled exception has occurred in a component in your application. If you click Continue, the application will ignore this error and attempt to continue."

I tried using Break, Throw, and Write-Error with a specified message and SilentlyContinue. All methods throw the same error box. Is there any way to suppress this error box?

Edit: Here's the error handling in my script:

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 is a text field in the Windows Form and $sBar is the status bar.

Here is what the error popup looks like:

Error Popup Window


Solution

  • So your PowerShell error is returning correctly. Its the Windows Forms that catches it and produces the error handling box that allows the user to move on. Check out this article by Adam Bertram. He talks about how to properly display errors in powershell windows forms.

    "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()
    

    On button click or when submitting content do the following:

    $button.add_Click({
     try
     {
         <strong>Get-Content</strong> -Path C:\File.txt
     }
     catch
     {
         $statusBar.Text = $_.Exception.Message    
     }
    })