trap{}
我在所有脚本中都有一个通用规则来处理和记录我没有通过 Try/catch 处理的所有不可预见的异常。
这很好用。
但是,当我有一个带有 windows 窗体的脚本时,所有异常都会自动显示为 .Net-popup,并且trap{}
不会执行里面的代码,因此永远不会记录错误。
简单示例:
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()
为什么陷阱被忽略?
以及如何让我的表单在出现异常时执行陷阱?
尤其是在具有 100 多个函数的脚本中,我不想trap{}
为每个函数添加一个(有效的)。