If a terminating error occurs in a PowerShell script used in a post-installation action the K2000 task engine will not spot it and will report that the task executed successfully despite the error.
This is normal due to the fact that when such errors happen in the PowerShell engine the return code to the Windows command line (ERRORLEVEL) is always 0.
The K2000 task engine looks for the ERRORLEVEL after executing a command and if it is different from 0 it becomes aware of the error.
To handle this situation and to make aware the task engine that something went wrong in the script it is possible to modify the code using the Exit-PSSession statement (or simply exit that is its alias) to return a not zero exit code.
Example:
#Original code
#Even if this code throws intentionally a terminating error the K2000 task engine will not spot it
…
…
throw “Personal Error Reason”
…
This need to be amended in this way:
#This script will handle the terminating error and set a non zero ERRORLEVEL
#The task engine will spot this error
try {
#put your code here
}
catch {
#we have an error…
exit 99
}
If catch is used without parameters like in this example it will catch all the errors.
To catch and handle different types of error is possible to specify the error to catch immediately after the catch statement.
For more information you can have a look to this excellent article about exception handling in PowerShell:
http://blogs.technet.com/b/heyscriptingguy/archive/2014/07/05/weekend-scripter-using-try-catch-finally-blocks-for-powershell-error-handling.aspx
Comments