Batch files to list all files and directories in a folder

DOS has always been handy for creating the type of batch files that XP could never handle well so here are a few scripts you might find useful.

List all files in a directory and subdirectory

Simple and straightforward this one, a script to list all files in a directory and all corresponding subdirectories. Copy the code into Notepad or other text editor and save it as get_files.bat:

echo off
for /r %%a in (*) do echo %%a >> get_files.txt

The for command here is used to run a further command for each file or folder in the set. The addition of the /r switch is to tell the script to recurse all directories and subdirectories from where the script is run.

The variable name %%a is used to hold the current folder being traversed.

The in (*) bit is the set of files to match, which in this case is everything denoted by using the * wildcard character.

The do echo %%a script executes the echo%%a command that simply displays the current file being read in the current folder name which is represented by the variable.

The final code >> get_files.txt directs and appends all the output to a text file called get_files.txt which is necessary because the script is repeated several times as it recurses each folder and so we want to collate all the names into a single file.

List all folders and sub-folders in a directory and subdirectory

A slight variation on the first script, this second one lists all folders and sub-folders in a directory and subsequent subdirectories. Copy the code into Notepad and save it as get_dirs.bat:

echo off
for /d %%a in (*) do dir /ad /on /s /b "%%a" >> get_dirs.txt

Let’s go through the code. The for command here is used to run a further command for each file or folder in the set. The addition of the /d switch is to tell the script to match against directory names only.

As before, the variable name %%a is used to hold the current folder being traversed and in (*) is the set of files to match, which again is everything denoted by using the * wildcard character.

The do dir /ad /on /s /b "%%a" bit executes the dir command on the current folder (denoted by "%%a") with a set of switches to produce the required output.

The /ad switch is to ensure that only directories and subdirectories are read since the purpose of the script is to list all folders only; the /on switch is to sort the directories in order of name; the /s switch is to ensure the dir command recurses all subdirectories and the /b switch produces the output in an easy-to-read format with no summary or header information.

A further change to this script is that the current folder variable %%a is enclosed by speech marks ". This is important because otherwise, any folder names that have spaces in them will not be read and a file not found message is returned.

The final code >> get_dirs.txt directs and appends all the output to a text file called get_dirs.txt which again is the important bit because the script is repeated several times for each folder and so we want to collate all the names into a single file.

List all files and folders in a directory and subdirectory to one level only

Here’s a specific variation on the above two scripts. Suppose I have a mass of directories and files archived from various backups and installations and need a list of all files and directories in a folder. Sounds easy enough but the catch is that I only want the script to traverse one level down in a directory since everything is archived by date.

So for example, my directory structure looks like this:

c:\backup\110201\… (a bunch of other directories and subdirectories under 110201)
c:\backup\110407\… (a bunch of other directories and subdirectories under 110407)

My script needs to recursively traverse all folders in c:\backup and provide me with a list of all files and subdirectories therein without drilling down into each and every single sub-directory.

Here’s the code of the batch file which we’ll call get_list.bat:

echo off
for /d %%a in (*.*) do dir /on "%%a" >> get_list.txt

Running get_list.bat in the c:\backup folder will then result in something like the following:




… and so on

One last point to bear in mind with all of the above scripts is that running the batch file multiple times will append the results onto the same text file.

Now go forth and script eager young script cadets!


64 Responses to Batch files to list all files and directories in a folder

  1. Nicolas says:

    echo off
    for /d %%a in (*.*) do dir /on “%%a” >> get_list.txt

    doesn’t give me what you say…

    • Grumpy Bear says:

      Well what does it give you then?

      I just tried it again in XP and it works perfectly! Copy the code into a text file and call it get_list.bat and then put the get_list.bat file in whatever directory you want to recurse. Open a command prompt and run get_list.bat which will create file called get_list.txt that contains the results.

  2. Jm Dollosa says:

    Great tutorial, thank you for this, now im inspired to write batch scripts, do you have any tutorials from basic to advanced batch scripting? Thanks!

  3. questorfla says:

    List dir and the otghers worked FINE for me! I ran from a command prompt inside the directory and got exactly what you said I would
    However :>) If I coculd ask a favor.
    I need to make a “link list” to all the index.php files inside folders that are two levels deep to make a printed list of website links.
    The top directory is the main site “”. the next directory webroot, has many subdirectories each of which may have 4 to 6 more subdirectories. While there are even more directories inside them, I only need to show just a single file in each: index.php.

    I am an “Old School” batch guy myself but you have me beat hands down on the switches :>).
    If i was in the “” folder and ran the command it should give me a printed directory list of all the different possible entry points.

    This is what I am after: “”

    then “…/a/2/index.php” etc. following through all the a,b,c,d folders to each of their 1,2,3 folders.

    I almost got your “list dir” to work but I had to take the results, delete the word “\webroot” from them and then I get rid of all the child directories after the “.com/a/1” parts keeping one from each group and adding the “index.php” by hand. Do you have any switches to let it show the\(skip webroot)\a\1\index.php” for each and then go to the next group?

    Any hope for this?

    • Grumpy Bear says:

      Sorry, but I don’t quite follow. What I’m hearing is that you want a script to show all index.php files in a directory and all sub-directories therein. A variation of the first script will work for this, copy it to your webroot and run:

      echo off
      for /r %%a in (index.php) do echo %%a >> get_files.txt

  4. Jay says:

    Trying to create a batch file that will use the files (file name with no extension) in a specified directory as choices/variables within the running batch file to be processed.


    C:\Temp\Files\ contains 6 files, each file contains text.
    – file1.txt
    – file2.txt
    – file3.txt
    – file4.txt
    – file5.txt
    – file6.txt

    When the batch file is executed it present the user with options/choices based on the files in the directory (this may vary depending on the amount of files in the directory) to perform additional tasks

    Select File to Copy:
    Press 1 for file1
    Press 2 for file2
    Press 3 for file3
    Press 4 for file4
    Press 5 for file5
    Press 6 for file6

    Pressing 1 would call another command “clip.exe” to copy the contents of the selected file to the clipboard.

    Is this possible?


    • Grumpy Bear says:

      Use a script like this and replace the ECHO Copy file x bit with your own commands.

      ECHO OFF
      ECHO Select file to copy
      ECHO Enter 1 for file 1
      ECHO Enter 2 for file 2
      ECHO Enter 3 for file 3
      ECHO Enter 4 for file 4
      SET /P RESULT=[Please choose (1/2/3/4)]
      ECHO You entered %RESULT%
      IF %RESULT% == 1 GOTO Option1
      IF %RESULT% == 2 GOTO Option2
      IF %RESULT% == 3 GOTO Option3
      IF %RESULT% == 4 GOTO Option4
      GOTO End

      ECHO Copy file 1
      GOTO End

      ECHO Copy file 2
      GOTO End

      ECHO Copy file 3
      GOTO End

      ECHO Copy file 4
      GOTO End


  5. Patrick says:

    very useful thanks!

  6. Kushal says:

    HI I need a batch file to list all java versions on my computer
    I tried using registry but failed what i want is something like this

    When i go to regedit\HKLU\Software\JavaSoft\Java Runtime Enviornment it should list all the names of the folder inside it on cmd itself

    Ex: If Under Java Runtime there are 2 folders
    1) jre
    2) jre

    It should display on cmd as

    Java Versions Installed: jre , jre

    • Grumpy Bear says:

      Try reading the JAVA_HOME environment variable to see where your Java directories are and then use a batch file to show all folders under that directory as per my example.

      Otherwise, if you have the Jav toolkit installed, there is getJREs() Javascript method that returns an array of all currently installed JRE’s.

  7. NewBiew says:

    I have a directory with files like


    I want to write a script which reads the directory and creates a new file build.txt (say) with below output/content

    PROMPT INS files


    PROMPT UPD files


    PROMPT CRT files



    I am a newbie to windows scripting. Can you please help?

    • Grumpy Bear says:

      Here you go:

      echo off
      echo PROMPT INS files >> get_files.txt
      for %%a in (ins_file*.txt) do echo @%%a >> get_files.txt

      echo. >> get_files.txt
      echo PROMPT UPD files >> get_files.txt
      for %%a in (upd_file*.txt) do echo @%%a >> get_files.txt

      echo. >> get_files.txt
      echo PROMPT CRT files >> get_files.txt
      for %%a in (crt_file*.txt) do echo @%%a >> get_files.txt

      • NewBie says:

        Thats awesome! You made it easier for me. Thanks so much!

      • NewBie says:

        I have some new requirement in addition to above example. I have some more files (in same folder) like below


        So, my first section of output should NOT list these ins*rollback*.txt files in get_files.txt

        i.e. I want to skip these ins*rollback*.txt files from being listed in first section of output. Because I need to list these rollback files separately which I will be doing using below code.

        echo PROMPT INS Rollback Files >> get_files.txt
        for %%a in (ins*rollback*.txt) do echo @%%a >> get_files.txt

        Let me know how to skip *rollback* files from each section.

  8. Joe says:

    These are great! How do I add a date and time stamp to:
    echo off
    for /r %%a in (*) do echo %%a >> get_files.txt

  9. papi says:

    very nice explanation

  10. FariZE_wrizj says:

    I have a directory like this


    And I have a batch file named test.bat in path A:\test.bat
    Assume that I doesn’t know the folder name.
    How can you make the test.bat copied to all folders in that current directory?
    I want to have this.


  11. MikeG says:

    I think I can make the get dirs work for what I need there are so may files that the little extra cut and paste will be worth it. What I cannot do is figure out how to get the bat to stop after 3 levels.
    C:\swsetup\sp55036\HDAQFE<<This is as deep as I need.
    C:\swsetup\sp55036\HDAQFE\srvrtm <<<but the batch keeps working to many more that are unneeded. How can I tell it to stop after the main rolder (in this case swsetup) the secondary folders(here I just showed sp55036 but there are many more) and then the next directpory (I guess that would be third level?).
    Then pickup again at:
    C:\swsetup\sp58427\x64… etc etc.there are sometimes 4 5 or 6 levels but I only need those first 3 to be in the list
    I hope this example made it a little clearer the btavh file runs too well 🙂 wont stop.

  12. Ed says:

    Hi, sorry I’m also new to this. Could you help please?

    I’m trying to search a folder (with subfolders) for files that need renaming (eg: instrumental.wmv.mp3 to instrumental.mp3).

    Is there a script to drag and drop a folder and search for an extention (.wmv.mp3) and rename it, leaving the new renamed file in it’s original directory/folder?

    Many Thanks

    • Grumpy Bear says:

      There’s a good example for you at which you can modify as required.

      Google is your friend 🙂
      (when it’s busy not snooping on everything you do)

      • eD says:

        This is what I have so far, but I cant’t seem to get this to look through subfolders. Please help.

        Also would is there a way of getting this to make a list (either showing it to me or by creating a text file)?

        @echo off
        set /p sourcefolder= drag the source folder here and press enter
        echo thankyou all files will be written without wmv on the end
        cd %sourcefolder%
        for /f “delims==” %%F in (‘dir /b *.mp3’) do ren “%%~nxF” “%%~nF”
        for /f “delims==” %%F in (‘dir /b *.avi’) do ren “%%~nxF” “%%~nF
        for /f “delims==” %%F in (‘dir /b *.wmv’) do ren “%%~nxF” “%%~nF”
        for /f “delims==” %%F in (‘dir /b *.mp3’) do ren “%%~nxF” “%%~nF”
        for /f “delims==” %%F in (‘dir /b *.avi’) do ren “%%~nxF” “%%~nF
        for /f “delims==” %%F in (‘dir /b *.wmv’) do ren “%%~nxF” “%%~nF”
        echo adding mp3 extension to everything
        ren “*” “*.mp3”

        Many Thanks

      • Grumpy Bear says:

        Try adding the /S switch to your dir commands which will recurse all sub directories.

      • Ed says:

        Hi, thanks for the help with /s to search subfolders but I’m still srtuggling to get it working. I’ve tried before and after /b and /f…am i tottally way off the mark on this?

      • Ed says:

        Hi, thanks for the help with /s to search subfolders but I’m still srtuggling to get it working. I’ve tried before and after /b and /f…am i tottally way off the mark on this?

  13. Joe Casey says:

    I would like to know the easiest way to move files older than 2 days using a batch file
    Thank you

  14. Ruth says:

    I was looking for a way to extract file names from a folder and found this: dir /a /b /-p /o:gen >filelisting.txt which I used to create a bat file.

    Can you tell me what I should add to the above so that the file list excludes the file extension?

    A line from the list that’s generated from the above appears as follows: Anne Rivers Siddons – The House Next Door.epub

    Any advice would be much appreciated … thank you.

  15. Ruth says:

    Ok, so I created a new bat file using the above. Should a new text file be generated with a list? There’s no new text file showing in the folder where I’m running the bat file from…

    Sorry, this is all new to me so appreciate your help.

    • Grumpy Bear says:

      There won’t be a new file generated, it will simply add to the file you already have there. Just delete the existing filelisting.txt file in your folder and then run the batch again. It’ll recreate the filelisting.bat with the results.

  16. Ruth says:

    Thanks, appreciate your help!

  17. kalim says:

    for /f “eol=: delims=”%%F in (‘xcopy “D:\Login\2013*” “D:\LOGIN2\2013\” /s’) do @copy “%%F” “D:\RESULT”

    It should copy the unique files from dir 1 by checking dir 2 and copying it to dir3 with same folder structure of dir1.

  18. kalim says:

    and any one help on above command as it not copying dir struc.

  19. Ian says:

    How can I just extract all file names from all subfolders. without the text file holding the directory structure?
    As your version below gives me folder names as well.

    echo off
    for /r %%a in (*) do echo %%a >> get_files.txt

    I am checking to see if I have missing files from two seperate drives, but the folder structure is different on both drives. So I was going to create the two text files of just file names and load it in to an excel spreadsheet to do a comparison.

    Many Thanks


    • Grumpy Bear says:

      Here you go:

      echo off
      for /r %%a in (*) do echo %%~nxa

      The ~ character is variable substitution, n is the filename only and x is the file extension only so the whole thing substitutes the variable containing the full path and file with the file name only.

  20. esp4yu says:

    Re-Script to Search for File or Folder, delete (if none then goto next), otherwise goto search for next file or folder to be deleted.

    Hi Grumpy,

    I tried to trash the previous post, I hope it it being removed already. Here is the repost as per your request….

    I was wondering it you could help me with a batch script file to remove all recycler folders and it’s content – it’s corrupted. I managed with just this:

    attrib -h -s N:\Recycler /s /d
    del N:\Recycler\*.* /f /s /q

    …but N is just a test folder. I have more than 15 partitions and it’s tedious doing this for each drive whenever I boot-up.

    I have tried rd /s /q C:\recycler it seems to work but every now & then I might plug in an external drive. Upon startup, the batch file will run but if the external drive is not attached, then I will have to ignore the error message.

    So it would be good if I could have a batch to search for recycler in each drive and if there is none, ignore and to goto the next and so forth until the process is completed.

    Appreciate your help, many thanks, Phillip

    • Grumpy Bear says:

      Hi Phillip,

      Try this:

      @echo off
      setlocal enabledelayedexpansion
      set “_DRIVE.LETTERS.FREE=Z Y X W V U T S R Q P O N M L K J I H G F E D C B A ”
      for /f “skip=1 tokens=1,2 delims=: ” %%a in (‘wmic logicaldisk get deviceid^,volumename’) do (
            cd /d %%a:\
            REM put your commands here to execute in the root directory of each drive

  21. Eta Beta says:

    First of all I must say what a great blog this is (and THANKS to all participants).

    I would like to have a rather simple .bat that lists only the name of the directory (on top of the .txt file) and (right below) only the folders contained in it (only the 1st level).

    Then I would like to have another .bat that does the same but includes also files and lists recursively (all levels).

    It would be very nice if one of the gurus on this amazing thread could provide some help. (I use both XP and Windows 8).

    Thanks in advance

    • Grumpy Bear says:

      There’s already an example to list the directories one level down and you can modify this so it aso lists the directory that the text file is in to give you the name of the directory above.

  22. Omprakaash Soundararajan says:

    you’re great n a genius in answering the questions.. i,ve read all the viewers question and u answered it according to their request accurately. hats off dude
    i need a help…
    i need to rename a huge folder contents, i got all their names ina txt file and i edited it like how i need it to be renamed, but i had to copy and paste to each n every file manually is there any bat file to rename according to their order. plz its bursting my head, am searching this for two whole days.. if you,re online i want talk with you. you’re brilliant, i tried all ur scripts above. am a no vice learning about the basic uses of computer

    • Grumpy Bear says:

      This all depends on what you want to rename those files to. If it’s arbitary e.g. file_x, sound_file, text_log then you’re better off doing it the way you have by dumping them all into a text file, editing the names and then appending each file with the rename command.

  23. Rita says:

    You are amazingly helpful. Could I pay you to write a bat file that i need completed? From a root directory, I need to search any number of sub-directories to look for specific files whose names are contained in a datafile. Once found, I need the file(s) moved into a separate directory. Not being a programmer, I need the help to do this and am looking for someone who seems to know what to do…Google brought me to this blog. You “get it”.!

    • Grumpy Bear says:

      Hi Rita,

      Try this:

      @ECHO OFF

      SET “DEST_DIR=%USERPROFILE%\Desktop\Folder”
      SET “SEARCH_DIR=C:\Temp”

      FOR /F “tokens=*” %%a IN (‘type %~dp0list.txt’) DO (
         FOR /R “%SEARCH_DIR%” %%f IN (*%%a*) DO (
            SET “SRC=%%~dpf”
            xcopy /S /I “%%~f” “!DEST!”

      This uses a file called list.txt containing your search terms on a new line. In the example above, the search directory is C:\Temp and any files found that match the search terms in list.txt are copied to a folder on your desktop. You can modify both of these by changing the paths for SET “DEST_DIR and SET “SEARCH_DIR as required.

  24. Dinesh Saraswat says:

    Great tutorial.. A well explained tutorial. The most I liked is the response, I see you have replied to almost all the queries posted. Great work keep it up.

  25. Matt says:

    Hi Grumpy,

    Just wanted to thank for you this again. One question, I’ve run into a problem of the number of files being larger than the text file can hold (or it’s timing out, not sure). Is there a way to just get the files added in the past day, week, etc? I guess I can just break it into chunks by temporarily moving all like a third of the folders into a new one and running the batch file from there, but I was hoping for a more efficient solution.


  26. Mike says:

    Hi Grumpy,

    I have a similar setup to your directory structure. Is there a way to get the batch file to return a list if files only located in directories ending in “apps” (i.e. only list the file found in c:\backup\110201\apps, c:\backup\110407\apps,… c:\backup\(various)\apps)?


  27. questor says:

    Unless I missed the answer already listed above, my problem is I need to go the other way. I have the text list of about 2000 pdf file names. Just the name, no path. the names includes commas and spaces along with various other allowed naming characters with name lengths being 30 to 40 characters long. There is no path listed at all.

    An example would be “Smith, John – Master of Ceremony at the Convention August 1976.pdf”.

    the list is just a text list of filenames like that.

    I need to use this list to search through a folder of 70,000 assorted pdf files finding only the matches to each filename on that list (if it exists) and copying that file if found to a flash drive.
    I have the list plus the files (or hopefully most of them) but I need a way to soft them out of the folder as a copy, not delete or move. And store that copy to a flash drive to take to another system

    I have tried my best to find a ay to use Robocopy or x-copy or even findstr with no real success. I did get one script to work but only for one file at a time., I can also enter one file at a time into Windows Search and find it but very slow and tiring.
    I is the reverse of the problem shown here but I am sure you have a solution.

    • Grumpy Bear says:

      If you got a script to work on one file at a time, it should be relatively simple to amend it so it recurses a list of filenames that you pipe into the script as an input.

  28. OldMovieMan says:

    I came here looking for a solution to a problem. The .bat file I had been using wouldn’t work in one folder. By substituting your .bat files above, I could finally see ‘access denied’ and realized I had to change my settings. That problem is now solved.

    But, you’ve opened me up to additional possibilities. The .bat file I use copies the names of directories and files alphabetically. I have both directories and files in a folder, How would it be written so that the names of all of the files within a directory would also be listed? I’d have to know what directory a particular file was in. There are sometimes 2 or 3 layers of directories, that is a directory within a directory within a directory. Am I making myself clear? I have a folder with 700 directories and 300 files. Each directory may have files or another directory with files in it. I’d like a list of every file and would need to know what directory it is in.

    Your assistance would be greatly appreciated.

    The .bat file I use is –> dir /b /o:en > dir.txt

  29. Magnes3d says:

    Thank you for posting this. I am starting to learn how to code and I really enjoy your style of teaching.

    I have read through this a couple of times but I am having a problem.

    Is there a switch that would allow only regular folders to be shown, and not System folders and hidden folders.

    • Grumpy Bear says:

      The Dir command has a switch /A that can be used to specify hidden folders. So Dir /AH for example, lists all directories including hidden ones. You can use Dir /AS to include system files and directories. To exclude hidden and system files and directories, just use Dir without any switches. None of my examples in the post have these switches for hidden or system files and directories.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: