Batch script to execute some commands in each sub-folder

You can tell the batch to iterate directories:

for /d %i in (C:\temp\*) do ( cd "%i" &  *enter your command here* ) 

Use a percent sign when run directly on the command line, two when run from a batch

In a batch this would look something like this:

@echo off
set back=%cd%
for /d %%i in (C:\temp\*) do (
cd "%%i"
echo current directory:
cd %back%

Put the commands you need in the lines between ( and ). If you replace C:\temp\ with %1 you can tell the batch to take the value of the directory from the first parameter when you call it. Depending of the amount of directories you then either call the batch for each directory or read them from a list:

for /f %i in (paths.lst) do call yourbatch %i

The paths.lstwill look like this:


All of this is written from memory, so you might need to add some quotations marks ;-) Please note that this will only process the first level of directories, that means no child folders of a selected child folder.

I like answer of Marged that has been defined as BEST answer (I vote up), but this answer has a big inconvenience.

When DOS command between ( and ) contains some errors, the error message returned by DOS is not very explicit.

For information, this message is

) was unexpected at this time.

To avoid this situation, I propose the following solution :

@echo off

pushd .
for /d %%i in (.\WorkingTime\*.txt) do call :$DoSomething "%%i"

exit /B


echo current directory: %1
cd %1
echo current directory: %cd%
cd ..

exit /B

The FOR loop call $DoSomething "method" for each directory found passing DIR-NAME has a parameter. Caution: doublequote are passed to %1 parameter in $DoSomething method.

The exit /B command is used to indicate END of method and not END of script.

The result on my PC where I have 2 folders in c:\Temp folder is

D:\@Atos\Prestations>call test.bat
current directory: ".\New folder"
current directory: D:\@Atos\Prestations\New folder
current directory: ".\WorkingTime"
current directory: D:\@Atos\Prestations\WorkingTime
Press any key to continue . . .

Caution: in Margeds answer, usage of cd "%%i" is incorrect when folder is relative (folder with . or ..).

Why, because the script goto first folder and when it is in first folder it request to goto second folder FROM first folder !

You should take a look at this. The command you are looking for is FOR /R. Looks something like this:

FOR /R "C:\SomePath\" %%F IN (.) DO (
    some command

On Windows 10 and later, it should be like this:

@echo off
for /D %%G in ("C:\MyFolderToLookIn\*") DO ( 

echo %%~nxG


This will show the name of each folder in "C:\MyFolderToLookIn". Double quotes are required. If you want to show full path of the folder, change echo %%~nxG with echo %%G