从powershell脚本退出会导致未处理的异常

时间:2017-10-18 05:15:04

标签: powershell exit-code exit

我在点击“否”按钮关闭表单后尝试执行exit,但exit导致系统错误

代码:

    function No {
            $Form.close()
            exit
    }
$NoButton.Add_Click({No}) 

如果没有退出,它会关闭表单,但会继续执行脚本

系统错误:

  

应用程序中的组件中出现未处理的异常。如果单击“继续”,应用程序将忽略此错误   试图继续。

     

系统错误。

完整按钮代码:

function No {
    $Form.close()
    exit
                    } #end No
# No button
$NoButton = New-Object System.Windows.Forms.Button 
$NoButton.Location = New-Object System.Drawing.Size(95,80) 
$NoButton.Size = New-Object System.Drawing.Size(80,20) 
$NoButton.Text = "No" 
$NoButton.Add_Click({No}) 
$NoButton.Cursor = [System.Windows.Forms.Cursors]::Hand
$Form.Controls.Add($NoButton) 

1 个答案:

答案 0 :(得分:0)

你需要等到$Form实际关闭,然后更好地杀死它自己的过程:

$NoButton = New-Object System.Windows.Forms.Button 
$NoButton.Location = New-Object System.Drawing.Size(95,80) 
$NoButton.Size = New-Object System.Drawing.Size(80,20) 
$NoButton.Text = "No" 
$NoButton.Add_Click({$Form.close()}) 
$NoButton.Cursor = [System.Windows.Forms.Cursors]::Hand
$Form.Controls.Add($NoButton)
$Form.Add_Closed({Stop-Process -ID $PID})    # Kill it's own process when the form is closed