Loop over Files in Directory from a Batch File

July 24th 2007 Batch

Figuring this out took me much longer than it should. The following line in a batch file will execute a command for each file in a directory:

for %%I in (C:\*.*) do echo %%~nxI

I had to overcome two obstacles to make this work:

  • When including the command in a batch file the % characters must be duplicated in comparison to the syntax for executing the command directly from the command line.
  • The ~nx prefix to the variable name causes only the filename with extension to be used instead of the complete path.
Copyright
Creative Commons License