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.

Get notified when a new blog post is published (usually every Friday):

If you're looking for online one-on-one mentorship on a related topic, you can find me on Codementor.
If you need a team of experienced software engineers to help you with a project, contact us at Razum.
Copyright
Creative Commons License