LastExitCode in PowerShell
This article will focus on
$lastexitcode commands and their difference in PowerShell.
Every scripting and programming language enables error handling, error catching, and managing in their scripts. We can use the
$? command and the
$lastexitcode command for error handling.
$? in a PowerShell Environment
It is important to understand the
$? command before using it here. According to PowerShell definitions of different commands, the
$? command can be used as an error handler.
Based on the last command executed, it returns a Boolean value,
False. If the last command executed in the script is successful, it returns
true; otherwise, it returns
One execution of this command is shown in the execution code below.
PS C:\Users> cmd /c "exit 5" PS C:\Users> $? False PS C:\Users> cmd /c "exit 0" PS C:\Users> $? True
This command example uses
exit with code
Exit with code
0 usually indicates a successful execution and termination of the script.
The following image shows the output of the
exit commands and the error handling done by
There is a difference in
$lastexitcode and the
$?. However, it is also used for error handling.
$LastExitCode as an Error Handler in PowerShell
There is a difference in error handling used when the command is internal and when the command is external.
You will use the
$lastexitcode when the command is external. This is because this command applies only to external scripts and commands.
$lastexitcode shows the last Windows-based program’s exit code.
The following script shows
$lastexitcode after the same command as above.
PS C:\Users> $LastExitCode 0 PS C:\Users>
The following image shows the same execution and output.
As the last command executed in the previous command gave
true as the output, this would show the successful execution of the last command. When the previous script was
$LastExitCode output would always be 0.
But, when it is unsuccessful, it would be 1 or any other integer returned by the external script because the
$LastExitCode command is not binary, unlike the