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

In this article, y'all're going to learn about 5 main types of IF statements you lot can employ in a Windows batch file, how the correct syntax looks, and a realistic instance for each.

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

1. Compare Values

1 of the basic things y'all'll usually demand to do in a batch script is compare ii values and follow a different course of activity depending on the comparison.

For example, let'southward say yous want to write a batch script that checks your figurer's difficult drive size daily. If it's below 3GB, you want to get an email report that says "Hard Bulldoze Space Too Depression."

To create a script that compares the current costless hard bulldoze space to your limit, you'll have to create the following batch script and save information technology as a .bat file.

          @echo            off
set DriveLimit=300000000
for /f "usebackq delims== tokens=2" %%ten in (`wmic logicaldisk where "DeviceID='C:' " become FreeSpace /format:value`) practise ready FreeSpace=%%ten
Echo FreeSpace="%FreeSpace%"
Repeat Limit="%DriveLimit%"
If %FreeSpace% GTR %DriveLimit% (
Echo There is plenty 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 utilize to pull data from your PC.

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

Now you can simply supplant the line Echo Not enough gratis infinite with a control to ship y'all an alert via electronic mail. Set the script to run daily.

2. Cord Comparisons

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

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

Some uses of this script would be for Information technology audits when you lot need to speedily run a script and brand sure the current operating organisation is the latest or whether it needs an upgrade.

Hither's what this script looks like:

          @echo            off
for /f "tokens=4-5 delims=. " %%i in ('ver') practice set VERSION=%%i.%%j
if "%version%" == "6.0" echo Windows Vista.
if "%version%" == "6.1" repeat Windows 7
if "%version%" == "6.2" echo Windows 8
if "%version%" == "vi.3" echo Windows viii.1
if "%version%" == "10.0" repeat Windows 10.

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

Batch File, Windows, Programming

The power 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 control, yous'll run across just how many statistics about your computer you lot can monitor.

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

3. Bank check If a File Exists

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

A lot of times, the batch job is merely a monitoring tool that you tin schedule to cheque for new incoming data files in a specific directory. Then, yous tin either copy that file over to another location or kicking 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 like shooting fish in a barrel. Hither'due south what that script looks similar:

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

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

For case, if you lot have a system or awarding running that creates new fault logs in a specific folder when there'southward a problem, y'all can run a batch job every then oftentimes. In this way, you can easily monitor whether new mistake logs are created and then you tin can transport an alarm.

iv. Cheque 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 effectually out there that are performing disquisitional It tasks like backing up of import files or running file copy operations. When these batch jobs fail, systems fail, and people unremarkably notice.

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

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

          @echo            off
xcopy C:
omefolder E:\backupfolder
IF %ERRORLEVEL% NEQ 0 <blat control to transport email>

If the awarding or control returns a zero, all is fine. If not, then you need to ship yourself an email.

However, you don't accept to take the email route. You lot tin can e'er write an mistake log that y'all might check every morn, or launch a second application or command that attempts to practise the re-create 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 mistake codes.

v. Check for Missing Parameters

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

For instance, allow'south say you've written a script that performs an xcopy command from an input folder to a mutual network binder used by a squad. The user only needs to follow your script proper name with the parameters defining their personal file path.

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

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

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

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

Batch Jobs Can Exist Powerful

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

In addition, you lot can often use more avant-garde programming languages and use PowerShell to reach many of the same tasks you currently use batch jobs for.

How to Use Windows Batch File Commands to Automate Repetitive Tasks

Read Next

About The Writer