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.