Auto-Repair Tool

How to execute batch file for every folder in a directory using a FOR Loop

Execute Batch File For Every Folder I’m a huge fan of batch scripts and AHK because they can make your life a lot easier, here’s how to execute a batch script for multiple folders individually.

Executing Batch Scripts On Multiple Folders

The command to execute a batch file within a batch file is CALL

Let’s see how to use it, combined with a FOR loop.

C:\DirectoryWithFolders = this is the folder where your subfolders are that you want to run a batch script on

C:\path\to\script.bat = this is the actual script

%%f = this is variable that stores the folder names

DO ( ) = this is how we execute multiple commands

CALL = this is how we execute the batch script

%1 = this variables passes on the folder name to the batch script we’re calling

The Actual Batch Script

Add the following code into a notepad editor and try it. Customize the folder paths to make it work for your purposes

FOR /f "usebackq delims=|" %%f in (`dir /b "C:\DirectoryWithFolders"`) DO (
cd "C:\path\%%f"
CALL C:\path\to\script.bat "C:\DirectoryWithFolders\%%f" %1)

Some Useful Additions

This works quite well for my purposes, but you might have to tweak it a little. Within the script.bat you should make sure to add this:

set basedir=%1
cd %basedir%

I’m not a master at batch scripts, so there could be some mistakes and easier ways to do this.

Always Include Quotes To Escape Folder Paths

Make sure to always escape paths with quotes or CMD might not be able to recognize paths with spaces in the folder paths. This is very important to know. Example cd “%basedir%” (including the quotes!!)

Check out our category of Productivity tips for additional nice AHK scripts and other batch scripts

Alternative Solutions: Auto-Repair Your PC And Drivers

Still Having Trouble? Try TWEAKBIT FIXMYPC - FREE

Published: Thursday, April 12th, 2012 Last Modified: April 13, 2012

Related Posts

Rate This Article
5 of 5 0 (100%) 1 vote