sudheer
sudheer

Reputation: 11

How to check if a file is existing or not using batch

I have a written a script to check if a file is existing or not and send me a mail on this. But its not working properly. Really appreciate if any suggestions or solutions provided.. My script is as below..

SET file1=E:\Program.* 

Set vLogFile=C:\logfile1.log 
if exist %file1% goto fileexists 
goto nofile 

:fileexists 
echo "File exist" > %vLogFile% 
--my required mail sending info here-- 
goto end 
:nofile 
echo "No file exist" > %vLogFile% 
--my required mail sending info here-- 
goto end 

Upvotes: 0

Views: 1312

Answers (4)

sudheer
sudheer

Reputation: 11

I got my issue resolved. Below is the script after I made changes and it is working fine now as per my requirements.

SET file1=Program 
Set vLogFile=C:\logfile1.log 
cd \ 
e: 
dir %file1% /s /b > %vLogFile% 
if errorlevel 1 ( goto mail1) else (goto mail2) 

:mail1 
--my code of lines for sending mail-- 
goto END 

:mail2 
--my code of lines for sending mail-- 
goto END 

:END

Upvotes: 1

Andriy M
Andriy M

Reputation: 77657

You are mentioning the type File in one of your comments. If I understand it correctly, you are talking about the file type as shown by Windows Explorer or the Properties dialog box. When writing batch files, however, it is easier to deal with file extensions. Now, the file type called simply File suggests to me that this file that you are trying to verify the existence of has no extension, i.e. its name is just Program, as opposed to Program.something.

However, the mask that you are using in the IF EXIST command, Program.*, would match both the Program with no extension and a Program with an arbitrary extension, i.e. Program.txt, Program.exe, Program.I.cannot.imagine.what.else etc. Perhaps, there's a Program file of a type other than File in the E:\ directory, and that causes the script to always call the :fileexists branch.

If you want to check for the existence of specifically Program, just specify the name as is, do not use the mask Program.*. In other words, change this line

SET file1=E:\Program.*

to this

SET file1=E:\Program

Upvotes: 0

foxidrive
foxidrive

Reputation: 41234

Do you have an :end label?

If you use goto :EOF instead of goto end then you don't need a label.

Upvotes: 3

captcha
captcha

Reputation: 3756

You need a better syntax with all double quotes:

@echo off
setlocal
SET "file1=E:\Program.*"

Set "vLogFile=C:\logfile1.log" 
if exist "%file1%" goto :fileexists 
goto :nofile 

:fileexists 
>"%vLogFile%" echo "File exist"
--my required mail sending info here-- 
goto end 
:nofile 
>"%vLogFile%" echo "No file exist"
--my required mail sending info here-- 
goto end 

Upvotes: 2

Related Questions