Recursive File Search - Batch
By: RainBawZAugust 9, 2015Here's a batch file I just wrote. It searches every drive available on the computer recursively for a given file. It can generate text and CSV logs.
How to use:
1: Copy the script below, save as a .bat file (e.g. "FileSearch.bat")
2: Place either in "C:\Users\-your username-\" or in System32. You can also place it elsewhere and CD to the directory in CMD.
3: The command name is the name of the .bat file. Valid arguments are: /L, /Q and /CSV in addition to the file, which should be enclosed in quotes if the file name contains spaces.
It returns errorlevels 1 and 0 depending on the search results.
SCRIPT::: ---SCRIPT START
@Echo off
setlocal enabledelayedexpansion
if "%1"=="" (
goto :error
)
if "%1"=="/?" (
goto help
)
set quiet=_
set log=_
set csv=_
set end_arg=
:params
shift
if "%~0"=="" goto :search
if /i "%~0"=="/L" (
set log=1
set searchlog=%time::=%
set searchlog=!searchlog:,=!
set searchlog=!searchlog:.=!
goto :params
)
if /i "%~0"=="/CSV" (
set csv=1
goto :params
)
if /i "%~0"=="/Q" (
set quiet=1
goto :params
)
Echo "%~0" | find /i "/" > nul
if !errorlevel!==1 (
set file=%~0
goto :params
)
:search
if not defined file goto :error
set cnt=0
for /f "tokens=2 delims==" %%Z in ('wmic logicaldisk get name /value') do (
Echo **%%Z**>tmp
for /f %%C in (tmp) do (
set disk=%%C
set disk=!disk:~2,-3!
if not !quiet!==1 (
Echo Searching !disk!\ drive...
)
for /f "tokens=*" %%A in ('dir "!disk!\!file!" /b /s 2^> nul') do (
for /f "tokens=*" %%I in ("%%A") do (
set pDrive=%%~dI
set pPath=%%~pI
set /a cnt+=1
if not !quiet!==1 (
if not !csv!==1 (
Echo Result !cnt!
Echo.
Echo File: %%I
Echo Disk: !pDrive!
Echo Disk location: !pPath!
Echo.
Echo ----------
) else (
Echo !cnt!,%%~dI,%%~pI,%%~nI%%~xI
)
)
if !log!==1 (
if !csv!==1 (
Echo !cnt!,%%~dI,%%~pI,%%~nI%%~xI>> !searchlog!.csv
) else (
Echo !cnt!: %%I >> !searchlog!.log
)
)
)
)
)
del /q tmp > nul
if not !quiet!==1 (
Echo Search complete
Echo.
)
)
Echo.
Echo Found !cnt! hits on !file!
Echo.
if !cnt! GTR 0 (
exit /b 0 & @Echo on
) else (
exit /b 1 & @Echo on
)
:help
Echo.
Echo FILESEARCH [/L] [/CSV] [/Q] ^<"file"^>
Echo.
Echo [/L] Writes the results to a .log file. The file is named after
Echo the time of the search.
Echo.
Echo [/CSV] Outputs results in CSV format for later parsing.
Echo If /L is provided, the CSV strings will be output to
Echo its own .csv file.
Echo.
Echo The CSV consists of the following:
Echo ^
,^,^,^
Echo.
Echo [/Q] Enables quiet searching.
Echo.
Echo ^ Specifies the search target.
Echo.
Echo If no file extension is provided, it will search folder names instead of
Echo file names.
Echo.
Echo FILESEARCH modifies the ERRORLEVEL variable.
Echo.
Echo ERRORLEVEL 0: Result found
Echo ERRORLEVEL 1: No result
Echo.
exit /b & @Echo on
:error
Echo.
Echo Syntax error. Use ^ for help.
exit /b & @Echo on
:: ---SCRIPT END
Need more help?
Describe your Problem
Example: Hard Drive Not Detected on My PC