How To Get List Of Files In A Folder In Batch Script

In this tutorial, you will learn how to get a list of files in a folder using a batch script. Batch scripts are widely used in Windows operating systems to automate tasks and simplify manual work.

They can be very powerful and useful, especially when combined with other command-line tools and external applications. By the end of this tutorial, you will have a working batch script that can list all the files in a specified folder.

Step 1: Create a new text file

To begin, create a new text file using Notepad or any other text editor you prefer. You can name this file anything you like, but for this tutorial, we’ll simply name it ListFiles.bat. Note the .bat extension; this is what makes the file a batch script.

Step 2: Write the batch script

In the newly created ListFiles.bat file, write the following script:

Let’s break down the code:

  1. @echo off – This command turns off the display of the command being executed.
  2. setlocal enabledelayedexpansion – This command enables the use of delayed variable expansion, which can be useful in batch scripts.
  3. set folderPath=%~1 – This command sets the variable folderPath to the first argument passed to the script.
  4. if "%folderPath%"=="" – This part checks if the folderPath variable is empty, meaning no argument was provided.
  5. echo Please provide a folder path as an argument. – This line displays an error message if no argument was provided.
  6. exit /b 1 – This command exits the script with an error code of 1.
  7. for %%A in (%folderPath%*) do ( – This command starts a loop that iterates through each file in the specified folder.
  8. echo %%~nxA – This command outputs the file name and extension.
  9. ) – This line ends the loop.

Step 3: Running the batch script

Save the ListFiles.bat file after writing the script. To run your batch script, open a Command Prompt window, navigate to the folder where your script is located, and type the following command:

Replace “C:\Path\To\Your\Folder” with the actual folder path containing the files you want to list.

Example Output:


Full Code:


In this tutorial, you learned how to create a batch script that lists all the files in a given folder. This simple, yet useful script can be further customized to suit your needs, such as filtering files by extensions, sorting results, or even processing the files in various ways.