Windows 10

Batch File To List Folders and Subfolders

In this tutorial, you’ll learn how to use a Windows batch script to list all folders and subfolders in a directory. This method is useful for system audits, file management automation, or folder indexing.

Batch files are text files containing a series of DOS commands that execute in sequence when the file is run.
 

đź§Ş Example 1: List Folders and Subfolders With Full Path

The following batch script recursively lists all folder and subfolder names with their full paths using the /R switch:

@echo off
for /d /R %%D in (*) do echo %%~fD

âś… Output:

C:\Users\StackHowTo\Docs
C:\Users\StackHowTo\Images
C:\Users\StackHowTo\Images\Class
C:\Users\StackHowTo\Download
  • for /d /R %%D in (*) — Iterates over each folder and subfolder recursively.
  • %%~fD — Returns the full path of the folder or subfolder.

 
 

đź§Ş Example 2: List Folders and Subfolders Without Full Path

If you only want the folder names without the full path, use %%~nxD instead:

@echo off
for /d /R %%D in (*) do echo %%~nxD

âś… Output:

Docs
Images
Class
Download

%%~nxD — Returns just the folder or subfolder name without the full path.
 

đź’ˇ Pro Tips
  • To save the output to a file, append > folders.txt to your echo command.
  • You can use wildcards like C:\MyDir\* in place of (*) to target specific paths.
  • Combine this with conditional logic to filter folder names (e.g., only list folders starting with “A”).
📚 Summary

By using the /R switch with the for /d loop in batch scripting, you can:

  • 🔍 Recursively list all folders and subfolders
  • đź§ľ Output results with or without full paths
  • đź’Ľ Automate file system audits and reports

This method is efficient, lightweight, and doesn’t require external tools.
 

🚀 Boost your productivity with the best AI tools → Try them

 

Leave a Reply

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