IT Knowledge Base

Technical Repository

HowTo: Powershell – Check to see if the previous command completed successfully

The completion status of the previous command can be accessed via the special variable $?.

This works best with non-terminating errors, terminating errors are the result of a direct throw or an exception getting thrown in .NET and they alter the flow of your code. Best to use a trap or try/catch statement to observe those type of errors.

One other thing to watch out for is that the returned value of ¬†$?¬†assumes an exit code of 0 means success (i.e. $? is set to $true) and anything else means failure ($? set to $false). Unfortunately not all console exe’s observe that exit code convention e.g. there may be multiple success codes and a single failure code (0). For those exes that don’t follow the exit code rules, use $LastExitCode as pointed out in the comments to determine success or failure.

Leave a Reply