views:

68

answers:

1

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

+1  A: 

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.

George Howarth
I tried this, but got a different error saying the pipeline had stopped. Also, Exit-PSSession doesn't seem to end the script either? The command doesn't error, but it just continues running after Exit-PSSession has executed.
Ben
It sounds like you just need to make use of functions and/or a Boolean value. If the test fails, just set a Boolean value somewhere to indicate that you don't want the rest of the script to be executed. So for example, before the block of code you don't want to be executed if the test fails, just put something like `if ($failed) { exit }`
George Howarth
Yep - with hindsight I think this is going to be the best way to go. Thanks for your help, George.
Ben