Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to copy a file (file.txt) inside all folders of a given destination. I want to create a batch file that does the job, but I'm not so skilled in Windows batch syntax.

share|improve this question
Please clarify: do you have a single source file that you want to copy to multiple destinations? (e.g. all the subfolders inside X:/SomeFolder)? – Roee Adler May 1 '10 at 15:41
Someting like copy myfile.txt to all folders found in d:\Destination – Remus Rigo May 1 '10 at 15:44
up vote 4 down vote accepted

You can use the advanced version of the for command available from Windows NT 4 onwards:

You need something like this in a batch file:

for /D %%f in ("%1\*") do copy "%2" "%%f\"

The batch file works as follows:

  • The first argument is the destination directory
  • The second argument is the file to be copied

The for command with the /D switch iterates over all directories in a given path (here: %1) and invokes a command on each iteration. Said command is the copy operation which copies the file into every directory.

Of course, since the batch file is only a single line you can also execute it directly on the command line. Just note that the variable for for has only a single %, then.

share|improve this answer
Ok, did a pretty much complete rewrite. Undo if you see the need but a few points to remember: (1) Using cd in a batch file is bad, since it leaves the caller in a completely different directory. If you can avoid it, do so and pushd/popd are usually the way to go if you need to temporarily change the directory. (2) Always surround arguments to commands with quotes if they might contain spaces. This holds especially true for path names. (3) Never ever do a for /f over the output of dir if you don't desperately need it. In the default configuration the console uses raster fonts – Joey May 2 '10 at 1:10
which causes all Unicode output to be converted into the (very) legacy OEM codepage, causing unaccented characters or question marks to show up. Have fun finding those names then. Since for is capable of iterating over files and directories, both in a certain folder and recursively in a tree you never need to use for /f and dir for those cases anyway. – Joey May 2 '10 at 1:12

You might want to read about Xcopy as well.

share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .