Saturday, September 18, 2010

Checking for Existence of a File in Batch Scripts

Sometimes it is necessary to check whether a file exists in a certain folder. Batch scripting provides a programmer with a really nice construction called 'If Exist'. It's pretty useful when you want to check for existence of a given file, for example, 'autoexec.bat'. To check for it, you should write the following code:
If Exist autoexec.bat Echo Autoexec.bat exists!
But if you try to check for existence of any files in the way described above, you'll be surprised. Written '*.*', you'll be notified about existing files anyway, even when there are no files in the given folder. So instead of using '*.*' in 'if exist', it's better to look at the following code:
@Echo Off
For %%a In (1\*.*) Do Call :File_Ex %%a
If Defined FileExist Echo Exist
Goto :EOF
:File_Ex
Set FileExist=Yes
Goto :EOF
This code will give you proper answer about files in the specified folder, and you can include it into your own batch scripts. Hope it'll be useful for you.

No comments:

Post a Comment

Translate