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

In this commodity, you're going to learn nearly five master types of IF statements you lot can use in a Windows batch file, how the right syntax looks, and a realistic instance for each.

If you're ready to starting time scripting, allow's become started.

1. Compare Values

One of the bones things you'll usually need to do in a batch script is compare 2 values and follow a unlike form of action depending on the comparing.

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

To create a script that compares the electric current free hard drive space to your limit, you lot'll have to create the post-obit batch script and relieve it as a .bat file.

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

In the script, WMIC is the Windows Direction 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 it into the FreeSpace variable.

Now you tin just replace the line Echo Non plenty costless space with a command to send you lot an alert via electronic mail. Ready the script to run daily.

ii. Cord Comparisons

Some other valuable IF comparison yous can do in a batch job is comparison strings.

In the post-obit example, you lot'll see how to bank check your Windows version using a batch job. Then you tin can compare this to your expected Windows version.

Some uses of this script would exist for It audits when yous need to quickly run a script and brand sure the current operating system is the latest or whether it needs an upgrade.

Here'south what this script looks like:

          @echo off
for /f "tokens=iv-5 delims=. " %%i in ('ver') do ready VERSION=%%i.%%j
if "%version%" == "6.0" echo Windows Vista.
if "%version%" == "half dozen.1" repeat Windows seven
if "%version%" == "6.2" repeat Windows 8
if "%version%" == "6.3" echo Windows 8.1
if "%version%" == "ten.0" repeat Windows 10.

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

Batch File, Windows, Programming

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

What'south more, you lot tin even apply scheduled batch jobs to get alerts on these.

3. Check If a File Exists

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

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

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

          @repeat 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 organisation or application running that creates new error logs in a specific folder when there's a problem, yous can run a batch job every so often. In this way, you can easily monitor whether new error logs are created so y'all tin can send an alert.

4. Check If a Command Failed

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

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

It's much smarter to get an alarm when your batch task has failed a control before people first noticing. This way, yous tin can fix the consequence proactively.

Yous can do this by utilizing the %errorlevel% variable that nearly applications and commands render after they are run. All y'all have to do is follow your command with the IF %ERRORLEVEL% command.

          @repeat off
xcopy C:
omefolder Due east:\backupfolder
IF %ERRORLEVEL% NEQ 0 <blat control to send email>

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

Even so, you don't have to accept the email route. You can always write an error log that you might check every morning, or launch a 2d awarding or command that attempts to do the copy using an alternate command.

Moreover, if you'd rather utilize an IF statement to bank check for specific error codes, Windows offers a pretty all-encompassing list of system error codes.

5. Check for Missing Parameters

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

For example, 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 squad. The user simply needs to follow your script name with the parameters defining their personal file path.

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

          @echo off
IF [%ane]==[] (
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, %ii is the 2d, and so on.

In full general, IF statements are too handy and yous don't demand to write too many codes to really employ them. Of course, if you lot want to step it up a notch, y'all might consider taking a look at VBA with our guide on creating your first VBA awarding.

Batch Jobs Can Be Powerful

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

In addition, you tin oft use more advanced programming languages and apply PowerShell to accomplish many of the aforementioned tasks you currently use batch jobs for.

How to Employ Windows Batch File Commands to Automate Repetitive Tasks

Read Next

Most The Author