Frage

I have a general trap{} in all my scripts to handle and log all unforeseen exceptions which I have not otherwise handled via Try/catch.

This works great.

But, when I have a script with windows forms, all exceptions will be displayed automatically as a .Net-popup and the code inside trap{} is not executed, so the error never gets logged.

Simple Example:

trap { Write-Host "This is written from inside the trap" }

[void][System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[System.Windows.Forms.Application]::EnableVisualStyles()

$form1 = New-Object 'System.Windows.Forms.Form'
$form1.ClientSize = '200, 150'
$button1 = New-Object 'System.Windows.Forms.Button' 
$button1.Location = '54, 45'
$button1.Size = '75, 23'
$form1.Controls.Add($button1)
$button1.add_mouseclick({ Testfunction })

function TestFunction { 
    $button1.falseproperty = 1  # this causes an exception  
}


TestFunction   ## this call of the faulty function gets trapped by the trap, the call from the button does not
$form1.ShowDialog()      

Why is the trap being ignored?
And how do I make my form execute the trap in case of an exception?
Especially in scripts with 100+ functions, I do not want to add a trap{} to each function (which works).

War es hilfreich?

Lösung

WinForms normally handles exceptions on the UI thread however you can subscribe to an event to handle those yourself:

[Windows.Forms.Application]::add_ThreadException({ ... })
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top