You are hereThe FOR Command

The FOR Command


By edwin - Posted on 05 January 2009

The FOR command is one of those commands that can save you hours of repetitive work. As a sysadmin its important to look for easy ways to get rid of repetitive tasks like renaming files or copying a select number of files. I recently had to retrieve 3,000+ files from a folder containing over 3,000,000 files. Imagine how long it would take to selectively find these files. The benefit of the FOR command is that it is a "looping" command. In other words, it will do a given task over and over until a given condition is met.

I had retrieved the list of files I needed from a database query. The list was placed in a simple test file (filelist.txt) like so:

00012345
00023451
00034512
00045123
00051234

XCOPY would allow me to copy the file from one place to another like this:

xcopy 00012345.* c:\results

The FOR command will allow me to run the xcopy over and over until the list is completed.

FOR /F %%A IN (filelist.txt) DO (XCOPY %%A.* C:\results)

This is probably the simplest form of this command. Here is a breakdown:

  • /F work with filesets
  • %%A represents a variable, also known as a replaceable parameter
  • (filelist.txt) the actual file set, can be more than one file or even a string
  • (XCOPY %%A.* C:\results) %%A will be replaced with each filename in the list

For more information: http://technet.microsoft.com/en-us/library/bb490909.aspx

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <blockquote> <img> <span>
  • Lines and paragraphs break automatically.
  • Pairs of<blockquote> tags will be styled as a block that indicates a quotation.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. The supported tag styles are: <foo>, [foo].
  • Images can be added to this post.

More information about formatting options