Windows command exit code

Every command or application returns an exit status, also known as a return status or exit code.

A successful command or application returns a 0, while an unsuccessful one returns a non-zero value that usually can be interpreted as an error code.

In Linux you can get the exit status of a last command by executing echo $?.

In this article i will show how to get the return code from the last console command or application in Windows using the command-line prompt (CMD) or the PowerShell.

Exit Code Of Last Console Command

Return True or False depending on whether the last console command or application exited without error or not:

# Windows CMD
C:\> if %ErrorLevel% equ 0 (echo True) else (echo False)

# Windows PowerShell
PS C:\> $?

Get the exit code of the last console command or application:

# Windows CMD
C:\> echo %ErrorLevel%

# Windows PowerShell
PS C:\> $LastExitCode

Exit Code Of Windowed Application

Return True or False depending on whether the last windowed application exited without error or not:

# Windows CMD
C:\> start /wait app.exe
C:\> if %ErrorLevel% equ 0 (echo True) else (echo False)

# Windows PowerShell
PS C:\> app.exe
PS C:\> $?

Get the exit code of the windowed application:

# Windows CMD
C:\> start /wait app.exe
C:\> echo %ErrorLevel%

# Windows PowerShell
PS C:\> app.exe
PS C:\> $LastExitCode

Was it useful? Share this post with the world!

Windows CMD exit codes indicate the success or failure of a command or script, providing a numeric status that can be used for error handling in batch files or scripts.

Here’s an example of checking the exit code after running a command:

echo off
your_command_here
if %errorlevel% neq 0 (
    echo Command failed with exit code %errorlevel%
) else (
    echo Command succeeded with exit code %errorlevel%
)

What Are Exit Codes?

Definition of Exit Codes

Windows CMD exit codes are numerical values returned by a command or script upon its completion. These codes provide insight into whether a command was successful or whether it encountered errors. Understanding exit codes is essential for diagnosing problems and improving the efficiency of your command-line operations.

Standard Exit Code Values

In CMD, exit codes typically adhere to a few standard values:

  • 0: Indicates that the command was successful without any errors. This is the exit code of success.
  • 1: Represents a general error. This code suggests that something went wrong, but it doesn’t specify the exact issue.
  • Common Codes (2-255): Various other codes may indicate specific types of errors or warnings based on the command executed. Familiarity with these can greatly aid troubleshooting.

Mastering Windows Cmd Switches: A Concise Guide

Mastering Windows Cmd Switches: A Concise Guide

How to Use Exit Codes in CMD

Basic Syntax for Checking Exit Codes

To check the exit code after running a command, you can use the built-in variable `%ERRORLEVEL%`. This variable holds the exit code of the last command executed. Here’s the basic syntax:

command
echo %ERRORLEVEL%

This simple approach allows you to receive immediate feedback on the success or failure of any command you’ve run.

Understanding Common CMD Commands and Their Exit Codes

Different commands in CMD can have their unique expected exit codes. Understanding these can help you troubleshoot effectively:

  • COPY: The `COPY` command is used to copy files. A successful copy returns an exit code of 0, while a failure (like a non-existent source file) results in 1.
  • DEL: The `DEL` command deletes files. Similar to `COPY`, success returns 0, and failure returns 1. If you try to delete a file that does not exist, you’ll receive an appropriate error code.
  • PING: Used for testing network connections. A successful ping returns 0, while unreachable targets will return 1.

Windows Cmd Clear: Refresh Your Command Line Effortlessly

Windows Cmd Clear: Refresh Your Command Line Effortlessly

Practical Examples of Exit Codes

Example 1: A Simple File Copy Operation

When you execute a command to copy a file, it’s helpful to check the exit code to verify that the operation was successful.

copy file.txt destination.txt
echo %ERRORLEVEL%

If the copy command succeeds, the output will display 0. If `file.txt` doesn’t exist, you will get an exit code of 1, indicating an error.

Example 2: Deleting a Non-Existent File

Attempting to delete a file that does not exist will also provide valuable insight into how CMD handles errors.

del nonexistentfile.txt
echo %ERRORLEVEL%

In this case, you should see an exit code of 1, signaling that the file couldn’t be deleted because it was never there in the first place.

Example 3: Using PING Command to Check Connectivity

The `PING` command is a practical and frequently used command to test network availability.

ping google.com
echo %ERRORLEVEL%

If you receive a successful response from Google, the exit code will be 0. If your internet connection is down or Google is unreachable, you will receive an error code of 1, indicating a failed connection.

Mastering Windows Cmd Route: A Concise Guide

Mastering Windows Cmd Route: A Concise Guide

Custom Exit Codes in Batch Files

Creating a Batch File with Custom Exit Codes

You have the ability to create custom exit codes in batch files, which can help streamline error handling and troubleshooting in your scripts. Consider the example below:

@echo off
if exist myfile.txt (
    exit /b 0
) else (
    exit /b 1
)

In this script, if `myfile.txt` exists, the script exits with a code of 0. If it does not exist, it exits with a code of 1.

Best Practices for Using Exit Codes in Scripts

Using meaningful exit codes in your scripts enhances both clarity and usability. Documenting your exit codes helps not only you but also others who may use or modify your code in the future. Consider establishing a standard to ensure consistency across your scripts.

Windows Cmd Repair Commands: A Quick Guide

Windows Cmd Repair Commands: A Quick Guide

Troubleshooting Common Exit Code Issues

Diagnosing Problems Using Exit Codes

Interpreting exit codes is a crucial skill for troubleshooting. By analyzing the return value of commands, you can pinpoint specific issues, whether it’s syntax errors, unavailable files, or other problems.

Logging and Monitoring Exit Codes

Setting up logging to capture exit codes during script execution can be immensely beneficial for debugging. By saving exit codes to a log file, you can track the history of your script’s operation and quickly identify which parts may be failing. Consider using tools or frameworks designed for logging CMD operations for a more organized approach.

Mastering Windows Cmd Remote Desktop: Quick Command Guide

Mastering Windows Cmd Remote Desktop: Quick Command Guide

Conclusion

Understanding windows cmd exit codes is invaluable for anyone looking to master the command line or improve their scripting and automation capabilities. By familiarizing yourself with standard exit codes and employing them in your scripts, you increase your productivity and troubleshooting efficiency. Regular practice and exploration of CMD’s capabilities will help solidify this knowledge, making it a crucial part of your skill set.

Windows Cmd Set Env Variable in Just a Few Steps

Windows Cmd Set Env Variable in Just a Few Steps

Further Reading and Resources

For deeper exploration into CMD and batch file programming, consider visiting official documentation, online tutorials, and community forums. These resources can provide ongoing insight and additional support as you continue to learn and implement CMD commands effectively.

Last Updated :
27 Jan, 2022

Return codes are the codes returned by programs when they are executed. If the command line is successful, it should return zero; if it is not successful, it should return non-zero. If the test fails, a non-zero value indicates the error number, and the user can attempt to resolve it by navigating to the error message.

The test may also return an exit code. A program’s or utility’s exit code usually appears when it finishes or terminates.

The list below includes some of the non-zero exit codes (with their respective errors) that programs may return

Error Code Description
0 Successful completion of the program.
This error indicates that the Windows command prompt has attempted to execute an unrecognized action
2 An error indicating that the file could not be found in the specified location
3 An error message indicated that the specified path could not be found.
5 An indication that the user is not authorized to access the resource
90090×2331 This error occurs when you misspell the command, application name, or path when configuring an Action.
2212254950xC0000017-1073741801 The error message tells you that Windows has run out of memory.
32212257860xC000013A-1073741510  This indicates that the user terminated the application
32212257940xC0000142-1073741502  The message indicating that the application was launched on a desktop to which the current user doesn’t have access

Batch file error level:

%ERRORLEVEL% is an environment variable that contains the last error level or return code in the batch file – that is, the last error code of the last command executed. Error levels may be checked by using the %ERRORLEVEL% variable as follows:

IF %ERRORLEVEL% NEQ 0 (
  DO_Something
)

A common method of returning error codes from batch files is to use the command EXIT /B %ERRORLEVEL%.

For custom return codes, use the EXIT /B <exitcodes> command.

Example:

 In the below example, if the condition is met, the script will terminate with the exit code 0. If the condition isn’t met, then the exit code will be 1.

if [[ "$(whoami)" != root ]]; then
   echo "Not root user."
   exit 1
fi
echo "root user"
exit 0

Output:

Output

Loops:

There have been statements enacted sequentially in the decision-making chapter. Alternatively, Batch Script can also be used to alter the flow of control in a program’s logic. These statements are then organized into flow control statements.

Serial No Loops Description
1 While Statement Implementation There is no direct while statement in Batch Script, although labels and an if statement can be used to implement this loop.
2 For Statement – List Implementations Batch files can loop using the “FOR” construct. In order to work with a list of values, the ‘for’ statement requires the following construct.
3 Looping through Ranges ‘For’ statements can also move through ranges of values. A general version is presented below.
4 Classic for Loop Implementation It has the classic ‘for’ statement found in many programming languages.
5 Break Statement Implementation Within any programming language, the break statement is used to alter the flow of control inside a loop. As part of looping constructs, the break statement causes the innermost enclosing loop to terminate immediately

Looping through Command Line Arguments

For checking command-line arguments, you can use the for statement. Here is an example of how to loop through the arguments of a command line using the ‘for’ statement.

for ((c=1; c<=7; c++))
do  
  echo "Welcome $c times"
done

Output:

Output

By Matthew Adams 🕜 Updated on April 22, 2025 at 1:30 pm

YouTube video · Monitor an FTP server & send file via email

Automation Workshop monitors files and folders on local & network or remote servers like Amazon S3 and SFTP, and executes Actions when files or folders are created, modified, or deleted according to defined conditions · Getting started · See more Automation videos

Let’s debug… the codes

Automation Workshop is a versatile tool that can handle complex automation scenarios including launching external apps therefore advanced error handling and debug capability is an essential part of process automation. Some Run Actions may complete with errorlevels or exit codes…

  • Run CMD Command · Advanced · Variables · Events 68000, 68002, 68202, and 68402.
  • Start App · Advanced · Variables · Events 67000, 67002, 67202, and 67402.
  • Terminate App · Options · Variables · Events 420000, 420001, and 420400.
  • Remote FTP Command · Options · Variables · Events 338000 and 338402.
  • Remote SSH Command · Options · Variables · Events 337000 and 337402.

…that indicate the termination status of executed Command or Application.

Exit codes

Program exit codes allow determining the specific reason for command’s or application’s termination. Although Automation Workshop shows codes in decimal format, they are also referred to as hexadecimal or negative decimal values.

Decisiveness on program exit codes

Code 0

Program successfully completed.

Code 1

Incorrect function.
Indicates that Action has attempted to execute non-recognized command in Windows command prompt cmd.exe.

Code 2

The system cannot find the file specified.
Indicates that the file can not be found in the specified location. Most likely the folder structure / path is configured correctly, however the file name is either misspelled or file is missing.

Code 3

The system cannot find the path specified.
Indicates that the specified path can not be found.

Code 4

The system cannot open the file.
A path to the file is specified correctly, however, the user credentials do not contain necessary permissions to the specified resource. Use Run As feature to grant access to a local file or network path.

Code 5

Access is denied.
Indicates that user has no access right to specified resource.

Code 259

0x103 · 103

The operation that was requested is pending completion. The process is still running.
The operation pending exit code 259 typically indicates that an application is still running and has not yet completed. However, custom applications may return any exit code, including the 259, as a custom termination status.

If your workflow relies on checking the running status of an application, and the application terminates with the code 259, it may result in an infinite loop waiting for a different exit code.

Code 9009

0x2331 · 2331 · 9,009

Program is not recognized as an internal or external command, operable program or batch file.
Indicates that command, application name or path has been misspelled when configuring the Actions—Run CMD Command or Start App.

Code 2147942545

-2147024751 · 0x80070091 · 80070091 · 2,147,942,545

The directory is not empty.
System attempted to delete a folder that was supposed to be empty but it isn’t. Extremely rarely, the Remove Folder Action may experience this error when deleting folders within a path of about 32,000 characters deep. In a few seconds/minutes Windows will enumerate files, and the problem will vanish upon retrying to remove the folder again.

Code 3221225477

-1073741819 · 0xC0000005 · C0000005 · 3,221,225,477

Access violation.
Indicates that the executed program has terminated abnormally or crashed.

Code 3221225495

-1073741801 · 0xC0000017 · C0000017 · 3,221,225,495

Not enough virtual memory is available.
Indicates that Windows has run out of memory. Observe Automation Workshop memory usage via the Operations Manager.

Code 3221225786

-1073741510 · 0xC000013A · C000013A · 3,221,225,786

The application terminated as a result of a CTRL+C.
Indicates that the application has been terminated either by user’s keyboard input CTRL+C, or CTRL+Break, or closing command prompt window.

Additionally, Windows Server 2025 exhibits a behavior where CMD commands and console applications, when launched under the new Windows Terminal instead of the legacy Windows Console Host, may encounter issues if started in rapid succession.

Due to a known bug, the terminal windows can become unresponsive, and after a certain number of these hung terminals accumulate, Windows automatically terminates them. This occurs without any user interaction—no CTRL+C or CTRL+Break input—yet the affected console applications exit with code 3221225786 (0xC000013A), potentially leading to confusion during diagnostics, as the exit code typically indicates an intentional user-initiated interruption.

Code 3221225794

-1073741502 · 0xC0000142 · C0000142 · 3,221,225,794

The application failed to initialize properly.
Usually for interactive apps a user with administrator rights is required. Moreover, the user must log on at least once to allow Windows to prepare the Windows Station and Desktop.

This error also may indicate that the application has been launched on a Desktop to which the current user has no access rights. Another less possible cause is that either gdi32.dll or user32.dll has failed to initialize.

Code 3221226505

-1073740791 · 0xC0000409 · C0000409 · 3,221,226,505

Stack buffer overflow / overrun.
Error can indicate a bug in the executed software that causes stack overflow, leading to abnormal termination of the software.

Code 3221225725

-1073741571 · 0xC00000FD · C00000FD · 3,221,225,725

Stack overflow / exhaustion.
Error can indicate a bug in the executed software that causes stack overflow, leading to abnormal termination of the software.

Code 3762507597

-532459699 · 0xE0434F4D · E0434F4D · 3,762,507,597

Unhandled exception in .NET application.
More details may be available in Windows Event log.

Code X

User-defined custom exit code.
Applications can return any predefined and custom codes, if they are programmed to do so. Additionally, Automation Workshop allows terminating apps directly from automated workflows providing any exit code. Valid value range: 0 through 4,294,967,295. The Terminate App Action supports a very flexible syntax for exit codes, for example:

  • 3221225786 · a regular integer that is popular in batch programming.
  • 3,221,225,786 · a number where thousands are comma-separated for easier readability.
  • 0xC000013A · hexadecimal exit code, commonly used in Windows applications and log files.

Help more?

For some error codes, Windows may provide a more friendly error message. NET HELPMSG displays information about Windows network messages (such as errors, warnings, and alerts). When you type NET HELPMSG and the error code (for example, net helpmsg 2182), Windows tells you more about the error code and may suggest actions to solve the issue.

net helpmsg 8

Not enough memory resources are available to process this command.

This will only work for Windows API Win32 error codes that originate from Microsoft Windows. If net help does not return a valid result, it can mean that the problem originates in external processes such as executed application or command syntax.

Save your time by automating!

Real users are utilizing Automation Workshop to automate tasks in Windows PCs and Windows Servers. It is the best Windows automation software and has been in the market since 2008. It is evolving rapidly to keep up with the constantly changing IT landscape.

Chuck W., quote about Automation Workshop

Automation Workshop is an awesome piece of software. It will save us thousands of man hours this year alone!—Chuck W.

Unleash productivity…

Automation videos · explore our extensive collection of video tutorials dedicated to guiding you through the creation of your own automation workflows. See a quick sneak-peek of our video library, offering you a glimpse into the extensive range of automation topics covered…

Auto-capture enclosed text

Synchronize SFTP server files & documents

Automate an FTP transfer

Automatic CPU pinning in Windows

Windows service automation

Automate SFTP uploads on Windows

Great success!

More Run…

  • Start App · Overview · Variables & Events
  • Run CMD Command · Overview · Variables & Events
  • Remote FTP Command · Overview · Variables & Events
  • Remote SSH Command · Overview · Variables & Events
  • Execute Script · Overview · Variables & Events
  • Open Document · Overview · Variables & Events
  • Start Task · Overview · Variables & Events
  • Stop Task · Overview · Variables & Events

More ways to Run…

  • API · Run Task using API
  • Remote Manager · Remote Operations · Remote deployment · Run Remote Tasks
  • Interactive · Desktop Shortcut · Tray Icon · Command line
  • Advanced fallback · On Task Error · On Action Error
  • Post-execution events

Discover

Automation Workshop includes many more awesome Triggers and numerous Actions to aid you to automate any repetitive computer or business task by providing state-of-the-art GUI tools.

FTP Watcher

Send Email

Automate now!

How automation works? A 90-second journey.

Just ask…

If you have any questions, please do not hesitate to contact our support team.

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.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Msvcr100 dll не обнаружен что делать windows 10
  • Аналог openvpn под windows
  • Как ускорить работу windows 10 на слабом ноутбуке
  • Win 10 проверка целостности системных файлов windows 10
  • Compare windows and linux