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 the 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 wanted to write a batch script that checks your computer’s hard drive size daily. If it’s below 3 GB 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’d 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. )
WMIC is the Windows Management Instrumentation component of Windows that comes with an assortment of commands you can use to pull PC information. 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 blat email command to send you an alert.
Finally, set this script up as a windows scheduled batch job that runs daily.
If you’ve never used blat before, we have an article that shows you how to set up blat. Unfamiliar with setting up scheduled jobs? We’ve got you covered with an article on how to set up Windows scheduled tasks .
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.
The ability to compare strings in batch opens up a whole list of possibilities. If you explore all of the information you can obtain out of a WMIC command you’ll see just how many statistics about your computer you can monitor. You can use scheduled batch jobs to alert 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 might be scheduled to check for new incoming data files in a specific directory.
Then, the batch job may either copy that file over to another location where it can be processed, or kick off some windows script that processes the file into an Excel output.
(We’ve written in the past about how to use Windows scripts for processing data to an Excel file ; some good background reading.)
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 to 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 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 by the IF %ERRORLEVEL% command. If the application or command returned a zero, all is fine. If not, then you need to send yourself an email.
@echo off xcopy C:\somefolder E:\backupfolder IF %ERRORLEVEL% NEQ 0 <blat command to send email>
You don’t have to take the email route. You could 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. Whatever action you want to take, IF %ERRORLEVEL% lets you do it.
If you’d rather use an IF statement to check for specific error codes, Windows offers a pretty extensive list of error codes.
5. Check for Missing Parameters
The last useful IF statement isn’t a specific command, but instead to check that the script received the appropriate input parameters.
For example, let’s say you’ve written a script that 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.
Obviously, you can’t properly execute your script without the path specified, so you may put an IF statement at the beginning of your script to make sure both parameters were entered.
Here’s how that looks.
@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.
Batch Jobs Can Be Powerful
Many people start using batch jobs for simple tasks that need to be executed in sequence. With IF statements it’s possible to add a lot more intelligence to your scripts.
You can often use more advanced programming languages like these, or learn to use PowerShell , to accomplish many of the same tasks you currently use batch jobs for.