How to run same cmd code across multiple folders

Abstract: Automate running commands across multiple subdirectories in Windows using a for /d loop to avoid manual navigation and path errors.

Created: 2026-09-16 by
To execute the same command across multiple folders in Windows 10, use a for /d loop within a batch script. This approach iterates through each directory and runs your target executable, such as ffmpeg for video conversion, ensuring that paths are handled correctly without breaking relative references. This method is significantly more reliable than manually navigating into each folder or using simple copy-paste operations. It automates repetitive tasks efficiently, saving time when processing large collections of media files. By leveraging built-in Windows command-line utilities, you avoid the need for third-party software or complex scripting languages like Python, provided you have basic familiarity with batch file syntax. The solution focuses on robust path handling to prevent common errors where scripts fail after the first iteration due to incorrect working directory states.

Understanding the Directory Iteration Logic

The core mechanism relies on the for /d command, which specifically targets directories rather than individual files. When you define a loop variable, typically %D, it represents the full path of each subdirectory found within your specified base location. This allows you to construct dynamic paths for input and output files inside the loop body. A critical mistake many users make is relying on relative paths without resetting the current working directory. If your script changes directories using cd but does not return to the original location, subsequent iterations may fail because the context has shifted unexpectedly. To prevent this, always use absolute paths for your base directory or ensure the script explicitly manages its working state. This ensures that every iteration starts from a known, consistent point, eliminating ambiguity in file resolution.

Constructing the Batch Script

Creating a reusable batch file is the most straightforward way to automate this process. You should create a new text file, name it with a .bat extension, and open it in a text editor like Notepad. Inside, you will define the base directory where all your source folders reside. This variable should be set at the top of the script for easy modification. Next, implement the loop structure. The syntax requires specifying the range of directories to scan. For example, if your videos are stored in subfolders of C:\Videos\Source, the loop will iterate through each of those subdirectories. Within the loop, you assign the current directory path to a variable and then execute your conversion command. It is vital to enclose paths containing spaces in double quotes to prevent the command interpreter from truncating the string at the first space character. Here is a corrected example that avoids the pitfalls of previous drafts:
@echo off
setlocal enabledelayedexpansion

REM Define the base directory containing all subfolders
set "BASE_DIR=C:\Users\YourName\Videos\InputFolders"

REM Check if the base directory exists
if not exist "%BASE_DIR%" (
    echo Error: Base directory "%BASE_DIR%" not found.
    pause
    exit /b 1
)

REM Iterate through each subdirectory
for /d %%D in ("%BASE_DIR%\*") do (
    echo Processing folder: %%D
    
    REM Construct input and output paths
    set "INPUT_FILE=%%D\input.mp4"
    set "OUTPUT_FILE=%%D\output.mp4"
    
    REM Verify input file exists before running conversion
    if exist "!INPUT_FILE!" (
        ffmpeg -i "!INPUT_FILE!" -c:v libx264 "!OUTPUT_FILE!"
    ) else (
        echo Warning: No input.mp4 found in %%D. Skipping.
    )
)

echo All folders processed.
pause
In this script, enabledelayedexpansion is crucial. Without it, variables inside the loop might not update correctly during execution, leading to stale data being used in subsequent commands. The ffmpeg command assumes the tool is installed and added to your system PATH. If it is not, you must provide the full path to the ffmpeg.exe executable within the script.

Handling File Paths and Spaces

Windows handles spaces in file names and directory paths by requiring quotation marks. In the example above, note how "!INPUT_FILE!" is quoted. Using exclamation marks instead of percent signs for variables inside loops is necessary when delayed expansion is enabled. This ensures that the variable expands at runtime rather than parse time, capturing the correct path for each specific iteration. If you encounter issues where the script skips folders or fails silently, check the console output for error messages from ffmpeg. Common errors include missing codecs or invalid input formats. Ensure that your source files match the expected format defined in your script logic.

Verifying and Testing the Automation

Before running the script on your entire collection, test it on a small subset of folders. Create a temporary directory with two or three sample subfolders, each containing a dummy video file. Modify the BASE_DIR variable to point to this test location. Run the batch file and observe the console output. Check if the output files were created in the correct locations. If they are, you can confidently apply the script to your main library. Always keep a backup of your original files before performing bulk conversions. Automated scripts can inadvertently overwrite existing files if the output filename already exists. Adding a unique identifier or timestamp to the output filename can mitigate this risk.

Related Resources

For further optimization of your workflow, consider reviewing guides on managing file structures. You might find How to Rename Multiple Files at Once in Windows useful for organizing your converted outputs. Additionally, understanding how to troubleshoot terminal issues is essential; see Every terminal is crashing in Windows 10 if you experience stability problems while running these scripts.

Frequently Asked Questions

What if ffmpeg is not in my system PATH?

You must specify the full absolute path to the ffmpeg.exe executable in your script. For example, replace ffmpeg with "C:\Program Files\FFmpeg\bin\ffmpeg.exe". This ensures the script can locate the tool regardless of environment variables.

Can I process only specific video extensions?

Yes, modify the for loop to target files instead of directories, or add an if statement to check the file extension. Use if "!INPUT_FILE:~-4!"==".mp4" to verify the suffix before executing the conversion command.

Why are my output files empty or corrupted?

This usually indicates an error in the ffmpeg command arguments or insufficient permissions. Check the console output for detailed error logs from the encoder. Ensure the destination folder has write permissions and that the input file is not locked by another application.

How do I skip folders that do not contain video files?

Include a conditional check using the if exist statement before calling the conversion tool. As shown in the code example, verifying the presence of the input file prevents errors and saves processing time on empty or misnamed directories.

Is it safe to run this script on network drives?

Running batch scripts on network drives can be slower due to latency. Ensure that the network connection is stable and that you have read/write access to both the source and destination paths. Consider mapping the network drive to a local letter for better performance.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More