Exception Powershell出口不工作

Exception Powershell出口不工作,exception,powershell,exception-handling,Exception,Powershell,Exception Handling,我正在编写一个脚本,该脚本检查注册表值,如果为0,则退出。(如果该值为1,则将继续。) 当我运行reg值为0的脚本时,它无法退出并引发异常: System.Management.Automation.ExitException: System error. at System.Management.Automation.FlowControlNode.Execute(Array input, Pipe outputPipe, ExecutionContext context) at

我正在编写一个脚本,该脚本检查注册表值,如果为0,则退出。(如果该值为1,则将继续。)

当我运行reg值为0的脚本时,它无法退出并引发异常:

System.Management.Automation.ExitException: System error.
   at System.Management.Automation.FlowControlNode.Execute(Array input, Pipe outputPipe, ExecutionContext context)
   at System.Management.Automation.ParseTreeNode.Execute(Array input, Pipe outputPipe, ArrayList& resultList, ExecutionContext context)
   at System.Management.Automation.StatementListNode.ExecuteStatement(ParseTreeNode statement, Array input, Pipe outputPipe, ArrayList& resultList, ExecutionContext context)
   at System.Management.Automation.StatementListNode.Execute(Array input, Pipe outputPipe, ArrayList& resultList, ExecutionContext context)
  ...
脚本正在使用windows窗体-不确定这是否相关

编辑:

我已将脚本简化为以下内容进行测试:

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

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

$Form.Add_Shown({ $Form.Activate(); start-sleep -s 3; exit; $form.close() })
$Form.ShowDialog()
这仍然会产生错误。如果我运行
启动sleep-s3;退出
非windows窗体上的代码它工作正常,因此问题似乎与windows窗体有关

谢谢


Ben

指定
退出
退出PSSession
具有相同的效果。查看stacktrace,我认为代码试图从另一个线程结束交互式会话,这就是它失败的原因


你只是想结束剧本吗?您可以尝试
[Runspace]::DefaultRunspace.CloseAsync()

Get item属性似乎不相关-这在我的测试中是正确的(尽管如果找不到路径,它将抛出)。我认为问题在于$form.close()。您需要展示更多内容(如何声明$form等)。请发布完整的脚本,以重现该问题?创建一个仍然重现问题的最小示例,并将其发布在此处。另外,您是否可以尝试通过命令行(即,不是从脚本文件)执行整个过程,并报告此错误是否仍然存在。请参阅上面的编辑-错误似乎与Windows窗体有关?如果测试失败,我希望脚本终止。此时它将关闭GUI窗口,但仍将继续运行脚本的其余部分:-(我尝试了此操作,但得到了另一个错误,即管道已停止。此外,Exit PSSession似乎也没有结束脚本?该命令没有错误,但它只是在Exit PSSession执行后继续运行。听起来您只需要使用函数和/或布尔值。如果测试失败,只需设置一个布尔值即可mewhere表示您不希望执行脚本的其余部分。因此,例如,在测试失败时您不希望执行的代码块之前,只需输入类似于
if($failed){exit}
Yep的内容-事后看来,我认为这将是最好的方法。感谢您的帮助,George。
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")

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

$Form.Add_Shown({ $Form.Activate(); start-sleep -s 3; exit; $form.close() })
$Form.ShowDialog()