Windows 10

Batch File to List All Files in a Folder and Subfolders

In this tutorial, you will learn how to use a batch file to list all files in a directory and its subdirectories. Batch files are scripts that automate DOS (Disk Operating System) commands in Windows environments.
 

📌 Example 1: List All .txt Files in a Folder and Subfolders

To list only text files (*.txt) recursively, use the forfiles command with the /s switch:

@echo off
forfiles /s /m *.txt /c "cmd /c echo @relpath"

✅ Output:

".\file1.txt"
".\file2.txt"
".\myFolders\test1.txt"
".\myFolders\test2.txt"
  • /s — Searches in all subdirectories.
  • /m *.txt — Matches all .txt files.
  • /c — Runs the specified command (in this case, echo @relpath to display the relative path of each file).
 

📌 Example 2: List All Files in a Folder and Subfolders

If you want to list all files of all types, modify the mask to *.*:

@echo off
forfiles /s /m *.* /c "cmd /c echo @relpath"

✅ Output:

".\file1.txt"
".\file2.txt"
".\image.png"
".\myFolders\nature.jpg"
".\myFolders\test1.txt"
".\myFolders\test2.txt"

This command will recursively scan all subfolders and return the relative path of every file.
 

🧠 Useful Tips

To list files with absolute paths, replace @relpath with @path:

forfiles /s /m *.* /c "cmd /c echo @path"

To filter by date, size, or modified time, you can use additional forfiles switches like:

  • /D — Filter by date.
  • /C "cmd /c if @fsize GTR 10000 echo @file" — List files larger than 10KB.
📚 Summary
Task Command
List all .txt files forfiles /s /m *.txt /c "cmd /c echo @relpath"
List all files forfiles /s /m *.* /c "cmd /c echo @relpath"
Show full file paths Use @path instead of @relpath
🚀 Boost your productivity with the best AI tools → Try them

Leave a Reply

Your email address will not be published. Required fields are marked *