Now that we've seen some of the extra commands that can be used in batch
files, let's play with one of the most powerful of them, the FOR command.
In this case, we're going to alter our simple backup batch file and make it a
bit more sophisticated. It's going to differentiate between two different
types of files (text/Word documents and pictures) and back each file type up to
a different directory. To set up for this we need to create two more
directories in c:\. Call them
Delete the existing text and .bmp files in your c:\testsource directory and
create a couple of new versions of each.
Now open notepad and enter the following:
for %%f in (*.doc *.txt) do xcopy
c:\testsource\"%%f" c:\text /m /y
for %%f in (*.jpg *.bmp *.gif) do xcopy
c:\testsource\"%%f" c:\pics /m /y
Now this is a bit more
complicated than the files we did before, so let's take a close look at what
this batch file is going to do.
Tells the computer that the directory we are going to be working in is
for %%F in (*.doc *.txt) do xcopy
c:\testsource\"%%F" c:\text /m /y
This line tells the computer that FOR any file with the .doc or .txt file
extension (meaning any standard Word doc or text file), DO an xcopy command to
copy that file to the c:\text directory using the same options we used in the
last batch file. The confusing looking '%%F' character represents the
variable that the FOR command uses to carry out this operation. For
example, if your first text file in the c:\testsource directory is
'texttest1.txt', the batch file would look at it, see that it had a .txt
extension and assign it as the value of '%%F'. The second part of the
do xcopy c:\testsource\"%%F" c:\text /m /y
takes whatever %%F is (in this case your 'texttest1.txt' file) and copies it
to the c:\text directory. The quotation marks around %%F are to allow the
command to deal with file names containing spaces. The command then
loops until it has looked at every file in the current directory before moving
on to the next part of the batch file.
for %%F in (*.jpg *.bmp *.gif) do xcopy
c:\testsource\"%%F" c:\pics /m /y
The only thing that is different here is that we are looking for graphics
file extensions instead and copying them to the 'c:\pics' directory.
Save your third batch file on the desktop as 'trickybackup.bat' and try it
out. You'll see that your newest creation neatly differentiates between
text documents and pictures and splits them up accordingly.