If … Else in Batch file

If you have ever used If .. Else in batch file then you know that how frustrating it is to work with it. In fact if you google this case then you will find that it is very common belief that ELSE doesn’t exits for BATCH files !!! I think it is just because very specific requirement to use this command is to write them in proper format.

Recently I had to add some “extra” feature in my backup script … an email notification via batch file for success or failure of operation. After spending many hours in forums finally I was able to figure out this mystery. Batch script will recognize If .. ELSE … only if it is written in following format,

IF <expression>(

..do this do that ….

) ELSE (

..do this do that ….


It is really weird but that’s how you can write IF .. ELSE expression in batch file.

I have created a sample batch file below to test this logic.

@echo off
rem COPY X:\test\file Y:\Some\Wrong\Address.txt

set Message="Operation Successful"
) ELSE (
set Message="Something is wrong"

@echo %Message%

Copy code above in notepad and save file as a batch file. If you run this code as it is, you will see “Operation Successful” message. Now remove “rem” in front of that copy command. This copy command is intended to be wrong to generate error and this will cause second message “Something is wrong” to appear. I used similar logic to change body of notification email.

That’s it for now…

It’s Just A Thought … Peace

Gaurang Sign

Leave a Reply

Your email address will not be published. Required fields are marked *