How can I perform a batch action on a list of files from the command line?

A. You can use the built-in "for" command to loop through a list of files. If you type the command

for /f "tokens=*" %a in ('dir /b *.*') do echo %a

the command outputs only the name of each file in the current folder, which the 'dir /b *.*' component can do all by itself. However, you can edit the "do" portion of the command to perform a secondary task. For example, you can add the name of a batch file and the %a parameter to call the batch file on each .msg file:

for /f "tokens=*" %a in ('dir /b *.msg') do datetime.bat %a

In addition to outputting the name of each file in the specified folder, this command adds the current date and time to the end of each .msg filename. If you use the command in a batch file, you need to add two percent (%) signs instead of one to access the parameters. For example, if you incorporate the above command into a batch file, you would type it as

for /f "tokens=*" %%a in ('dir /b *.msg') do datetime.bat %%a

Learn more from "Command-Line Argument FAQs" and "Harness the Power of the Command Line."

Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.