Using Exit Codes in PowerShell
When you launch one application from another application, there are two common approaches, you can either Fire-and-Forget, or you can wait for the application to complete and then make sure it performed properly, usually by checking the exit code of the application.
The exit code is an easy way for an application to signal to its caller what the result was, typically success or failure, but really could be just about anything. The exit code is just an integer, and its meaning is entirely up to the developer, but there are some common exit codes in specific environments (I'll leave that task to the reader to find if there are common exit codes for their project). Almost always an exit code of 0 indicates success.
Max Trinidad has written a nice blog post describing how to set and use exit codes within PowerShell. To set an exit code, use a function like this...
Try
{
## Do Something here...
}
Catch
{
#Write-Host "Error in function";
$err1 = 1;
}
Finally
{
if($err1 -eq 1)
{
## - Custom Exit Code:
[Environment]::Exit("99");
}
Else
{
Write-Output $result;
[Environment]::Exit("0");
}
}
If this code were in a function, you could execute the function and then check the exit code. In Max's case, he create a Division function...
PowerShell -noexit -command { `
cd 'C:\Users\Max\Documents\SAPIEN\PrimalForms 2011\Files'; `
& ./DivideNow.ps1 40 5}
$LastExitCode
PowerShell -noexit -command { `
cd 'C:\Users\Max\Documents\SAPIEN\PrimalForms 2011\Files'; `
& ./DivideNow.ps1 40 0}
$LastExitCode
For a complete example, visit Max's blog.
In the case of PowerWF you may have a case where you want to execute a PowerShell function that resides in a seperate PS1 file from within a PowerWF script block. You could then use the $LastExitCode variable to insure that the function executed properly.
Technical Note: if you deploy a PowerWF workflow that relies on an external PS1 file or executable, that file will need to be accessible to the deployed workflow.