If you do a lot of work in Windows batch files, the IF statement offers a very powerful way to add flexibility to your scripts.

In this article, you're going to learn about five main types of IF statements you can use in a Windows batch file, how the correct syntax looks, and a realistic example for each.

If you're ready to start scripting, let's get started.

1. Compare Values

One of the basic things you'll usually need to do in a batch script is compare two values and follow a different course of action depending on the comparison.

For example, let's say you want to write a batch script that checks your computer's hard drive size daily. If it's below 3GB, you want to get an email report that says "Hard Drive Space Too Low."

To create a script that compares the current free hard drive space to your limit, you'll have to create the following batch script and save it as a .bat file.

        @echo off
set DriveLimit=300000000
for /f "usebackq delims== tokens=2" %%x in (`wmic logicaldisk where "DeviceID='C:'" get FreeSpace /format:value`) do set FreeSpace=%%x
Echo FreeSpace="%FreeSpace%"
Echo Limit="%DriveLimit%"
If %FreeSpace% GTR %DriveLimit% (
 Echo There is enough free space.
) else (
 Echo Not enough free space.
)

In the script, WMIC is the Windows Management Instrumentation (WMI) component of Windows that comes with an assortment of commands you can use to pull information from your PC.

This is how the "wmic" command in this script calls the logicaldisk space and places it into the FreeSpace variable.

Now you can just replace the line Echo Not enough free space with a command to send you an alert via email. Set the script to run daily.

2. String Comparisons

Another valuable IF comparison you can do in a batch job is comparing strings.

In the following example, you'll see how to check your Windows version using a batch job. Then you can compare this to your expected Windows version.

Some uses of this script would be for IT audits when you need to quickly run a script and make sure the current operating system is the latest or whether it needs an upgrade.

Here's what this script looks like:

        @echo off
for /f "tokens=4-5 delims=. " %%i in ('ver') do set VERSION=%%i.%%j
if "%version%" == "6.0" echo Windows Vista.
if "%version%" == "6.1" echo Windows 7
if "%version%" == "6.2" echo Windows 8
if "%version%" == "6.3" echo Windows 8.1
if "%version%" == "10.0" echo Windows 10.

Here's what the output of this script looks like:

Batch File, Windows, Programming

The ability to compare strings in a batch opens up a whole list of possibilities. If you explore all of the information you can obtain from a WMIC command, you'll see just how many statistics about your computer you can monitor.

What's more, you can even use scheduled batch jobs to get alerts on these.

3. Check If a File Exists

Another useful situation where an IF statement in a batch file is to check for the existence of a data file.

A lot of times, the batch job is just a monitoring tool that you can schedule to check for new incoming data files in a specific directory. Then, you can either copy that file over to another location or kick off some Windows script that processes the file into an Excel output.

Using a batch file to check whether a file exists in a directory is quick and easy. Here's what that script looks like:

        @echo off
if exist c:\temp\datafile.txt (
 %WINDIR%\SysWOW64\cmd.exe
 cscript LoadToExcel.vbs
) else (
 rem file doesn't exist
)

The IF EXISTS comparison is useful for a lot of things.

For example, if you have a system or application running that creates new error logs in a specific folder when there's a problem, you can run a batch job every so often. In this way, you can easily monitor whether new error logs are created so you can send an alert.

4. Check If a Command Failed

An aspect of batch file scripting that too few IT folks or programmers use is checking for errors.

There are a lot of batch jobs floating around out there that are performing critical IT tasks like backing up important files or running file copy operations. When these batch jobs fail, systems fail, and people usually notice.

It's much smarter to get an alert when your batch job has failed a command before people start noticing. This way, you can fix the issue proactively.

You can do this by utilizing the %errorlevel% variable that most applications and commands return after they are run. All you have to do is follow your command with the IF %ERRORLEVEL% command.

        @echo off
xcopy C:\somefolder E:\backupfolder
IF %ERRORLEVEL% NEQ 0 <blat command to send email>

If the application or command returns a zero, all is fine. If not, then you need to send yourself an email.

However, you don't have to take the email route. You can always write an error log that you might check every morning, or launch a second application or command that attempts to do the copy using an alternate command.

Moreover, if you'd rather use an IF statement to check for specific error codes, Windows offers a pretty extensive list of system error codes.

5. Check for Missing Parameters

The last useful IF statement isn't for a specific command but instead to check that the script received the appropriate input parameters.

For instance, let's say you've written a script that performs an xcopy command from an input folder to a common network folder used by a team. The user just needs to follow your script name with the parameters defining their personal file path.

You can't properly execute your script without the path specified, so you may want to put an IF statement at the beginning of your script to make sure both parameters are entered.

        @echo off
IF [%1]==[] (
GOTO sub_message
) ELSE (
xcopy %1 E:\backupfolder
)
GOTO eof
:sub_message
echo You forgot to specify your path.
:eof

If you've never used parameters with batch scripts before, the percent symbol followed by a number represents the parameter variable. %1 is the first parameter, %2 is the second, and so on.

In general, IF statements are too handy and you don't need to write too many codes to actually use them. Of course, if you want to step it up a notch, you might consider taking a look at VBA with our guide on creating your first VBA application.

Batch Jobs Can Be Powerful

Many people started using batch jobs for simple tasks that need to be executed sequentially. Thankfully, with IF statements, it's possible to add far more logic to your scripts.

In addition, you can often use more advanced programming languages and use PowerShell to accomplish many of the same tasks you currently use batch jobs for.