Windows Batch File Looping Through Directories to Process Files?

Solution 1:

You may write a recursive algorithm in Batch that gives you exact control of what you do in every nested subdirectory:

@echo off
call :treeProcess
goto :eof

:treeProcess
rem Do whatever you want here over the files of this subdir, for example:
for %%f in (*.tif) do echo %%f
for /D %%d in (*) do (
    cd %%d
    call :treeProcess
    cd ..
)
exit /b

Solution 2:

Aacini's solution works but you can do it in one line:

for /R %%f in (*.tif) do echo "%%f"

Solution 3:

Jack's solution work best for me but I need to do it for network UNC path (cifs/smb share) so a slight modification is needed:

for /R "\\mysrv\imgshr\somedir" %%f in (*.tif) do echo "%%f"

The original tip for this method is here

Solution 4:

Posting here as it seems to be the most popular question about this case.

Here is an old gem I have finally managed to find back on the internet: sweep.exe.
It executes the provided command in current directory and all subdirectories, simple as that.


Let's assume you have some program that process all files in a directory (but the use cases are really much broader than this):

:: For example, a file C:\Commands\processimages.cmd which contains:
FOR %%f IN (*.png) DO whatever

So, you want to run this program in current directory and all subdirectories:

:: Put sweep.exe in your PATH, you'll love it!
C:\ImagesDir> sweep C:\Commands\processimages.cmd

:: And if processimages.cmd is in your PATH too, the command becomes:
C:\ImagesDir> sweep processimages


Pros: You don't have to alter your original program to make it process subdirectories. You have the choice to process the subdirectories only if you want so. And this command is so straightforward and pleasant to use.

Con: Might fail with some commands (containing spaces, quotes, I don't know). See this thread for example.