knot22
knot22

Reputation: 2768

if/then/else logic in batch file

I am writing a batch file that zips up MS Access 2010 files (file extension .accdb), renames the zip file with the date and time, then moves the zip file to a subfolder called Backups. The following shows the code so far:

 @echo off
 "C:\Program Files\VMware\VMware Tools\zip.exe" backup.zip *.accdb
 for /f "tokens=1-5 delims=/ " %%d in ("%DATE%") do (set thedate=%%g-%%e-%%f)
 for /f "tokens=1-3 delims=/:" %%a in ("%TIME:~0,8%") do (set thetime=%%a-%%b-%%c)
 set thetime=%thetime: =0%
 rename backup.zip %thedate%_%thetime%.zip
 move %thedate%_%thetime%.zip .\Backups
 %SystemRoot%\explorer.exe .\Backups

This is working fine. However, I'd like to add a check at the beginning to see if there are any users with open Access files (occurs if there are *.laccdb files) prior to performing the zip operation. The desired logic is:

  1. check if there are any *.laccdb files
  2. if there is/are *.laccdb file/s then send user a message to close Access files and abort batch file
  3. if no *.laccdb files are found then proceed with the zip operation (as written in the code above)

How do I add this IF/THEN/ELSE type logic to the batch file and how do I check for *.laccdb files?

Upvotes: 0

Views: 302

Answers (1)

Magoo
Magoo

Reputation: 80013

if exist *.laccdb (echo Send the message) else (echo continue the processing)

is the full format. Naturally, the echo statement can be any series of statements you like, eg.

if exist *.laccdb (
 echo Send the message
 goto sendmessage
)
rem the file does not exist, so carry on with the ZIP operation
... your ZIP operation goes in here
goto :eof

:sendmessage
rem put whatever code you want to send the message in here.
goto :eof

Note that goto :eof is very specific, it requires the colon and means "go to the end of this batch file" It's intrinsic to cmd - the label should not be user-declared.

The format of the if is also specific.This syntax is required:

if condition (
 dothis_if_true
) else (
 dothis_if_false
)

The positioning of the parentheses is critical. The first open must be on the same physical line as the if (or do) and if an else is used then both the preceding ) and succeeding ( must occur on the same physical line as the else.

Upvotes: 1

Related Questions