且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Powershell退出不起作用

更新时间:2023-02-06 11:56:54

指定 exit Exit-PSSession 具有相同的效果。看堆栈跟踪,我认为代码试图从不同的线程结束交互式会话,这就是为什么它失败。



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


I am writing a script which checks for a registry value and and exits if is 0. (It will proceed if the value is 1.)

  if ((Get-ItemProperty -path HKLM:\SOFTWARE\ICT\LoginScript).proceed -eq 0) {

        $form.close()
        exit             

        } 

When I run the script with the reg value at 0, it fails to exit and throws an exception instead:

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)
  ...

The script is using windows forms - not sure if that is relevant?

EDIT:

I have reduced the script to the following to test:

[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()

And this still gives the error. If I run the start-sleep -s 3; exit code on a non-windows form it works fine, so it looks like the issue is tied in with Windows Forms.

Thanks,

Ben

Specifying exit has the same effect as Exit-PSSession. Looking at the stacktrace, I think the code is attempting to end the interactive session from a different thread, and that's why it fails.

Are you just trying to end the script? You could try [Runspace]::DefaultRunspace.CloseAsync() instead.