SCCM OSD form script exit with code

I am working on a new script that runs during our SCCM OSD to collect the computer name.
It uses Windows Form controls to do this.
I have a button on the form which should terminate the script with a code so I can inspect the code on later task sequence steps.
Trouble is that everything I have tried so far to exit with a code causes and exception to be thrown.
The code is naturally in the OnClick event of the button.
I tried ‘Exit 200’ and ‘$host.SetShouldExit(200)’ but both throw an exception. How do I exit with a code in this situation please?



Hi David,

I’ve used a script in the past to do things like this and it seems that sometimes exiting scripts before the form is ready for you to do it, can cause this behaviour.

I’ve noticed if you make sure to store your exit codes and close the form, then deal with exiting using your exit codes a bit later, things work without throwing an exception, since I imagine the form has had time to do a little dance while closing down.

Unfortunately I don’t quite understand enough about how the underlying mechanism works that causes this, but I can seem to work around the bits that cause me issues!

Here is an example Gist:

If you exit at line 34, in the function Set-OSDComputerName, you will get an exception. However, if you store it in a variable that’s in the scope of the script, then use the exit keyword down just after the Load-Form call on line 73, this does seem to work.

Thanks! That worked.