捕获未处理的异常

时间:2019-01-30 15:39:14

标签: powershell exception

我正在尝试捕获Powershell使用Windows窗体生成的异常情况;

目前我能够捕获使用try / catch语句终止错误,并已研究数后,仍然它显示了未处理的异常错误对话框,我想不会出现。

尝试捕捉,似乎并没有帮助。

Function Get-Choice{
Try{
$ErrorActionPreference = 'Stop'
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")

[void][System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")

$Form3 = New-Object System.Windows.Forms.Form

$Form3.Text = "Please Make A Choice From Below"

$Form3.ClientSize = New-Object System.Drawing.Size(390, 160)

$form3.topmost = $true

$Text = New-Object System.Windows.Forms.Label

$Text.Location = New-Object System.Drawing.Point(15, 15)

$Text.Size = New-Object System.Drawing.Size(300, 80)

$Text.Text = "What would you like to do today? `n`n 1. Find the Permissions of a folder `n 2. Find Who Has Access to a Folder `n 3. Find out what shares are on a server`n 4. Select a csv that contains a list of shares"

$Form3.Controls.Add($Text)

#$ErrorActionPreference = "SilentlyContinue"

Function Button1

{

$Button1 = New-Object System.Windows.Forms.Button

$Button1.Location = New-Object System.Drawing.Point(15, 100)

$Button1.Size = New-Object System.Drawing.Size(125, 25)

$Button1.Text = "1. Folder Permissions"

$Button1.add_Click({Folder

$Form3.Close()})

$Form3.Controls.Add($Button1)

}

Function Button2

{

$Button2 = New-Object System.Windows.Forms.Button

$Button2.Location = New-Object System.Drawing.Point(145, 100)

$Button2.Size = New-Object System.Drawing.Size(100, 25)

$Button2.Text = "2. Folder Access"

$Button2.add_Click({Members 

$Form3.Close()})

$Form3.Controls.Add($Button2)

}

Function Button3

{

$Button3 = New-Object System.Windows.Forms.Button

$Button3.Location = New-Object System.Drawing.Point(250, 100)

$Button3.Size = New-Object System.Drawing.Size(130, 25)

$Button3.Text = "3. Shares on a Server"

$Button3.add_Click({Shares 

$Form3.Close()})

$Form3.Controls.Add($Button3)

}

Function Button4

{

$Button4 = New-Object System.Windows.Forms.Button

$Button4.Location = New-Object System.Drawing.Point(145, 128)

$Button4.Size = New-Object System.Drawing.Size(100, 25)

$Button4.Text = "4. Auto Shares"

$Button4.add_Click({Auto 

$Form3.Close()})

$Form3.Controls.Add($Button4)

}

Button1

Button2

Button3

Button4

[void]$Form3.showdialog()
}
Catch[System.Exception]{
}
}
}
Get-Choice

未示出的处理的异常对话框但脚本终止

2 个答案:

答案 0 :(得分:0)

将您在try-catch-Blocks中的Click事件中调用的函数括起来以“处理”异常:

Function Button1
{
$Button1 = New-Object System.Windows.Forms.Button
$Button1.Location = New-Object System.Drawing.Point(15, 100)
$Button1.Size = New-Object System.Drawing.Size(125, 25)
$Button1.Text = "1. Folder Permissions"
$Button1.add_Click({
Try{
    Folder
}catch{<# Maybe something here #>}
$Form3.Close()})
$Form3.Controls.Add($Button1)
}

答案 1 :(得分:0)

因此,通过在代码中使用return而不是exit来解决此问题,并编写为尝试捕获,

感谢您的@ T-Me帮助