Monday, August 8, 2011

Search for a File on Local Drives

We all need sometimes to find a certain file on a local disk drive. It is not hard to implement search by name with the help of batch files. But what to do if you need to search for a file on all the drives available on a computer? The example script below shows how to perform it.
@echo off
setlocal
for %%i in (c d e f g h i j k l m n o p q r s t u v w x y z) do (
for /f "tokens=*" %%a in ('dir /b /s /a-d %%i:\FileName.ext 2^>nul') do (
set "foundFile=%%a" & goto found
))
echo File not found
goto :EOF
:found
echo File found - %foundFile%

As far as you can see, we simply look through all letters for logical drives and then search for the needful file on the each drive separately.

1 comment:

  1. I would like to use something like this to detect whether a file with a certain extension exists somewhere in a sub-folder of a specified folder, but I can't seem to get it to work. Can you help? Thanks.

    - There may be any number of *.ext files anywhere in the tree, or none.

    - The batch file must quit if one *.ext file is found anywhere in the tree, and execute a command (unrelated to the found file) if no *.ext files are found.

    The file searched for is a lock file whose presence means "do not process anything in this folder tree" but it can appear anywhere in the folder tree and be any name.

    ReplyDelete

Translate