This tutorials explains about list files in a directory.

dir command used to list files and folders in a directory.

/b option bare format allows you to list only files and directories names.

dir /b

Output:

.gitignore
node_modules
package-lock.json
package.json
print-ulid.js
README.md
src

It display file and directory names in a current directory, not subdirectories names. src is a directory name, remaining all are file names.

To exclude a directories names, use /a-d option

dir /b /a-d

Output only file names.

.gitignore
node_modules
package-lock.json
package.json
print-ulid.js
README.md

TO print file names inside a sub folder, use /s option

dir /b /s

Batch script to print the file names

For writing a script file

  • Open any text editor or VSCode
  • Create a new file and name the file as info.bat

There are multiple ways we can print the file names

  • using dir command

use the dir command and result of the filenames piped to filename.

@echo off

dir /b /a-d > filenames.txt
dir /b "c:/work" /a-d > worknames.txt


On running the info.bat file,

  • @echo off: commands execution does not print the commands

  • first dir command, creates filenames.txt created , contains file names in a current directory where script executes

  • second dir command,worknames.txt created with filenames list in the directory specified(c:/work)

  • using for loop

for loop in batch used to iterate each file in a directory and print the file name

@echo off

set "folder=."

for %%I in ("%folder%\*") do (
    echo %%~nxI
)

Following are steps

  • Current directory is set to . in a variable folder
  • Iterate each file name in a folder give,
  • %%I is a varialbe to points to file object
  • %%~nxI used to print the file name, n is the file name, x contains extension.
  • use %%~nI to get only file name without extension.
  • you can change folder variable point to any other folder that can be path to an directory.