Derley mad
Derley mad

Reputation: 73

Copying multiple files by *.extension with xcopy

I'm making a batch script to copy all .doc, .pdf, .xls etc from disk to a pendrive.

My current code below:

@echo off
Title ""

::All Docs
 XCOPY C:\*.doc W:\xdatabase /C /S /I /F /H > W:\database\XC\AllInf.txt

::All PDFs
 XCOPY C:\*.pdf W:\xdatabase /C /S /I /F /H >> W:\database\XC\AllInf.txt

::All WRI
 XCOPY C:\*.wri W:\xdatabase /C /S /I /F /H >> W:\database\XC\AllInf.txt

::All TXT
 XCOPY C:\*.txt W:\xdatabase /C /S /I /F /H >> W:\database\XC\AllInf.txt

::All PPT
 XCOPY C:\*.ppt W:\xdatabase /C /S /I /F /H >> W:\database\XC\AllInf.txt

::All XLS
 XCOPY C:\*.xls W:\xdatabase /C /S /I /F /H >> W:\database\XC\AllInf.txt

The question is: How can I add more extensions but avoid all that duplication in the code?

Upvotes: 4

Views: 11772

Answers (2)

johny why
johny why

Reputation: 2201

This works on one line, no script-file needed. Needs single percent-sign, not double:

for %f in (xlsm xlsb) do xcopy SourceDir\*.%f DestinationDir\ /S

or in your case

for %e in (doc pdf xls wri txt ppt xls) do XCOPY C:\*.%e W:\xdatabase /C /S /I /F /H > W:\database\XC\AllInf.txt

according to my tests, robocopy supports multiple extensions without a loop.

ROBOCOPY C:\ W:\xdatabase /S *.doc *.pdf *.xls *.wri *.txt *.ppt *.xls

However, in my experience xcopy seems to beat robocopy on speed, even with multiple extensions, but i only tested with a very small batch of files.

Upvotes: 2

Tomalak
Tomalak

Reputation: 338108

Always true, in all programming languages: If you have to do a thing multiple times in a row, use a loop.

@echo off
Title ""

for %%e in (doc pdf wri txt ppt xls) do (
    XCOPY "C:\*.%%e" W:\xdatabase /C /S /I /F /H > W:\database\XC\AllInf.txt
)

The for loop can be tricky in batch scripting. A handy guide is here: http://ss64.com/nt/for.html

Upvotes: 17

Related Questions