The command prompt or the Windows PowerShell is the terminal equivalent in the Unix world. Similarly, you may come across instances where you need to determine whether a command executed successfully.
This is especially useful in automated commands such as PowerShell and Batch scripts where the execution of a previous command can impact the execution of the rest of the program.
Checking If a Command Succeeded in Windows
In Windows, you can use the the
exit status still exists like that in Unix-systems. However, instead of
$? (unless it's PowerShell), we use the variable
%errorlevel% to check if a command succeeded.
Consider the example below:
C:\> mkdir dir
C:\> echo %errorlevel%
In this example, the
mkdir command creates a new directory named
echo %errorlevel% command then prints out the exit status of the
mkdir command. If the directory is successfully created,
echo %errorlevel% will output
Just like in Unix-like systems, you can use this mechanism in batch scripts to perform different actions depending on whether a command succeeds or fails.
Here's an example of a batch script that uses the
:: Execute a command
:: Check if it succeeded
if %errorlevel% equ 0 (
echo The command succeeded.
) else (
echo The command failed.
This script attempts to create a directory. If the command succeeds, it will print "The command succeeded."
If it fails (perhaps because you don't have permission to create a directory in the current location), it will print "The command failed."
Knowing how to check if a command succeeded can be incredibly useful when dealing with command-line interfaces, particularly in situations where automation and scripting are involved.