Skip to main content

How to Run a Command on Every File in a Directory in Batch Script

One of the most powerful uses for a batch script is to automate a repetitive task. A very common scenario is needing to perform the exact same action on every single file in a folder. You might need to rename, move, compress, or process a batch of files, and doing so manually is tedious and error-prone. The definitive tool for this job in Windows Batch is the FOR loop.

This guide will teach you how to use the standard FOR loop to iterate through all files in a directory that match a specific pattern. You will learn how to use the loop variable to pass each filename to another command, making it simple to build powerful batch processing scripts.

The Core Command: The FOR Loop

The FOR command is the primary tool for iteration in batch scripting. In its simplest form, it is designed to loop through a set of files that match a given pattern.

Syntax: FOR %%F IN (file_pattern) DO (command)

  • FOR: The command to start the loop.
  • %%F: The loop variable. In each iteration, this variable will hold the name of the file that is currently being processed. You can use any letter from A-Z.
  • IN (file_pattern): The set of files to process. This is where you use a wildcard (like *.*) to select your files.
  • DO (command): The action to perform. This command will be executed once for every file found.

Basic Example: Echoing Every Filename

This is the "Hello, World!" of FOR loops. It finds every file in the current directory and simply prints its name to the screen.

@ECHO OFF
ECHO --- Listing all files in the current directory ---
ECHO.

REM The (*.*) pattern matches all files.
FOR %%F IN (*.*) DO (
ECHO Found file: "%%F"
)

ECHO.
ECHO --- Done ---

Output (in a folder with two files):

--- Listing all files in the current directory ---

Found file: "document.txt"
Found file: "image.jpg"

--- Done ---

How the FOR Loop Works

The command FOR %%F IN (*.*) DO ... instructs the command processor to:

  1. Look in the current directory.
  2. Create a list of all items that match the pattern *.* (which means any name and any extension).
  3. For the first item in the list, assign its name to the %%F variable (e.g., %%F becomes "document.txt").
  4. Execute the command(s) in the DO block.
  5. For the second item in the list, assign its name to %%F (e.g., %%F becomes "image.jpg").
  6. Execute the command(s) in the DO block again.
  7. Continue until every item in the list has been processed.

Using Wildcards (* and ?) to Filter Files

The real power comes from using wildcards in the IN() clause to be more specific.

  • *: Matches any number of characters.
  • ?: Matches any single character.

This script will only process files that have a .log extension.

@ECHO OFF
ECHO --- Archiving all .log files ---

FOR %%L IN (*.log) DO (
ECHO Archiving file: "%%L"
REM (Imagine a MOVE or ZIP command here)
)

Other examples:

  • ("image_*.jpg"): Matches image_01.jpg, image_final.jpg, etc.
  • ("report_2023_??.txt"): Matches report_2023_01.txt, report_2023_12.txt, but not report_2023_1.txt.

Common Pitfalls and How to Solve Them

Problem: The Loop Includes Subdirectories

If you use (*) as your pattern, the FOR loop might include the names of subdirectories in its list, which can cause errors if your command only works on files.

Solution: There is no simple switch for this. The most robust way to ensure you are only processing files is to check the file attributes inside the loop. The ~a modifier can be used, but a simpler check is often to see if the item has a file extension.

FOR %%I IN (*) DO (
IF "%%~xI" NEQ "" (
ECHO "%%I" is a file, not a folder.
)
)

Problem: Handling Filenames with Spaces

If a filename contains spaces, it can break commands inside the DO block if not handled correctly.

Solution: Always enclose the loop variable in double quotes. This is a critical best practice. The examples above all use "%%F", which ensures that a filename like "My Report.txt" is treated as a single, complete string.

Practical Example: A "Convert Images" Script

This script simulates a common batch processing task. It finds every .bmp (Bitmap) file in a folder and calls a hypothetical ImageConverter.exe tool to convert each one to a .png file.

@ECHO OFF
SETLOCAL
ECHO --- Batch Image Converter ---
ECHO Searching for .bmp files to convert...
ECHO.

IF NOT EXIST "ImageConverter.exe" (
ECHO [ERROR] The ImageConverter.exe tool was not found.
GOTO :End
)

FOR %%B IN (*.bmp) DO (
ECHO ------------------------------------
ECHO Found BMP file: "%%B"

REM Get the filename without the extension using the ~n modifier
SET "BaseName=%%~nB"

ECHO Converting to "!BaseName!.png"...

REM Call the command-line tool, passing the input and output names.
ImageConverter.exe -in "%%B" -out "!BaseName!.png"
)

:End
ECHO.
ECHO --- Conversion process finished ---
ENDLOCAL

Conclusion

The FOR loop is the definitive tool for batch processing files in a directory. It provides a simple and powerful structure for iterating through a set of files and executing a command on each one.

Key takeaways for using it successfully:

  • Use the syntax FOR %%F IN (pattern) DO (command).
  • Use wildcards (like *.txt) in the IN clause to select which files to process.
  • Always enclose your loop variable in double quotes ("%%F") inside the DO block to correctly handle filenames with spaces.
  • Use tilde modifiers (like %%~nF for the name or %%~xF for the extension) to deconstruct the filename for more advanced operations.