How to Check if Command Executed Successfully in Windows

In this tutorial, we'll explore various methods of checking if a command succeeded focusing primarily on Windows systems.

How to Check if Command Executed Successfully in Windows

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%
0

In this example, the mkdir command creates a new directory named dir.

The echo %errorlevel% command then prints out the exit status of the mkdir command. If the directory is successfully created, echo %errorlevel% will output 0.

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 %errorlevel% variable:

@echo off

:: Execute a command
mkdir dir

:: 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."

Conclusion

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.

Table of Contents
Great! Next, complete checkout for full access to GeekBits.
Welcome back! You've successfully signed in.
You've successfully subscribed to GeekBits.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info has been updated.
Your billing was not updated.