Understanding how to retrieve the exit code of the last command executed is crucial for scripting, automation, and error handling in Windows environments. The exit code provides valuable information about the outcome of the command: a return value of 0 usually signifies a successful execution, while non-zero values typically indicate an error or a specific condition. This numeric code serves as a communication mechanism between scripts or programs and the operating system. This tutorial explains how to get exit code of last command on Windows.
CMD
On Windows, the ERRORLEVEL
is a special environment variable that holds the exit code of the most recently executed command. When a command is executed, it returns an exit code to the operating system.
For instance, in the Command Prompt (CMD) run the ipconfig
command. To get the exit code of the last command, simply type the following command:
echo %ERRORLEVEL%
It returns 0 that indicates that the previously executed command was successful.
PowerShell
In PowerShell, the $LASTEXITCODE
automatic variable holds the exit code of the most recent native program (Win32 application) that was executed. It's important to note that it does not capture the exit code of PowerShell cmdlets.
$LASTEXITCODE
In PowerShell, the $?
automatic variable offers the execution status of the last command. It holds a value of True
if the last command succeeded and False
if it encountered a failure. Notably, this variable is capable of reporting on both Win32 applications and PowerShell cmdlets.
Leave a Comment
Cancel reply