Using the FOR command to copy files listed in a text file

A coworker asked me for a script. Here’s the request:

… would want to copy all files on this list [an attached text document] to another location (doesn’t really matter where for now). All are currently located in \\server\share\folder. The path in the new location should begin with the part after “folder”…

In a nutshell, here is the high-level description of what the script must do:

Given a text file which provides a list of files, copy the files from a fixed source to a fixed destination, recreating the directory trees on the destination. A simple file copy won’t work because there may be files in the source folders which should not be copied.

Sample content of the text file is:

client\CD120\Samarai Legends\Drafts\drafts folder.txt
client\CD120\Samarai Legends\Inbox\Legends.doc
client\CD120\Bushido Warriors\Inbox\Warrior Code.doc

The solution to this is to make a simple batch file that parses the content of the text file, generating the appropriate xcopy command to copy the file. We’ll call the batch file xcopylist.bat; its one line of content is below. Change c:\temp\ to whatever path you want the files copied to. (I used c:\temp\ for testing.) Change \\server\share\folder to the root folder of the files to copy.

for /f "delims=" %%i in (filelist.txt) do echo D|xcopy "\\server\share\folder\%%i" "c:\temp\%%i" /i /z /y

Put the file list in the same directory as the batch file and name the file list filelist.txt. Then run the batch file and viola! You’ve got to love the for command, which lets you (among other things) parse text files and use the line-by-line output. Another trick in here is the output parser pipe, which allows us to automatically press the “D” key with each xcopy command.

Note: The batch file overwrites files in the destination automatically. To turn this off (have it prompt you), change /y to /y- in the batch file. However, if you’re using Windows NT 4.0, just delete the /y switch altogether – it’s only supported in Windows XP and Windows 2000.

128 comments to Using the FOR command to copy files listed in a text file

  • Happy Guy

    Thanks Brian for this nice solution. It saved a lot of time for us :)

  • Joe


    I would like to implement your script to backup starred picasa photos, these are stored in a file named starlist.txt in the format:

    C:\Users\Joe\Pictures\Play\Journeys\New Years 08\IMG_1682.JPG
    C:\Users\Joe\Pictures\Play\Journeys\New Years 08\IMG_1683.JPG

    The problem being that your script uses the whole file path when duplicating the files, resulting in the following (unusable) address:

    C:\temp\C:\Users\Joe\Pictures\Play\Journeys\New Years 08\IMG_1682.JPG

    Is there a simple modification that can be made to the script which would remove the “C:\Users\Joe\Pictures” element from the created file path?

    Many thanks in advance for your assistance.

  • The simples thing is to make a copy of starlist.txt, do a search/replace removing all text c:\users\joe\pictures, and running the script against that.

    As far as I can remember (it’s been a while), there is no easy way to truncate or replace data in strings from within the Windows shell.

  • Joe

    Many thanks for your fast response!

    I modified starlist.txt as you suggested, so that each line reads as follows:
    \Play\Journeys\Spain 05\Chris’s Photos\DSCN0319.JPG

    This duplicated the files successfully, but put each individual image into a folder with the image name, within the correct folder structure e.g:
    D:\Starred Photos\Play\Journeys\Spain 05\Chris’s Photos\DSCN0319.JPG\DSCN0319.JPG

    I am using the following command:
    for /f “delims=” %%i in (starlist.txt) do echo D|xcopy “C:\Users\Joe\Pictures%%i” “D:\Starred Photos\%%i” /i /z /y

    Do you have any suggestions on why the folder is being created?

    • Modify the following excerpt of code:
      echo D|xcopy

      To the following:
      echo F|xcopy

      XCOPY prompts the user to either copy F, file, or D, directory. When changed from D to F, the batch script was able to successfully copy only the photos files to the directory, without placing each photo in a self named directory.

  • Only thing I can think to try is adding a backslash after the folder “Pictures” in the path “C:\Users\Joe\Pictures%%i” (that is, make it “C:\Users\Joe\Pictures\%%i”

  • Manuel

    Hi Brian, this script is very useful, i apreciate to much if you can help me to modify
    a little this script.
    I´ve a filename.txt file with the names of the files something like these



    But the really I need is copy the files with your relative path to another folder

    thanks and regards


  • Not 100% sure what you need… You mention a relative path — relative to what?

    Something you can do to help explain may be to give an example of one line in the text file, and an example of how the script would use that line. For example, if one line was this:


    … and you wanted to generate this:

    copy test.txt c:\files\test.txt

    … the script would be:

    for /f “delims=” %%i in (filelist.txt) do copy “%%i” “c:\files\%%i”

    Give me an illustrative example and I’ll help if I can.

  • Manuel

    Hi Brian,

    Supose that I got a file “filelist.txt” with this content



    but these files (test.txt, test1.txt, etc…) are in a differents folders, something like that


    I need copy all of the contents in the “Temp” folder, to another folder “Final”, but including the same folder structure of the “Temp” folder, see below

    c:\Final\ \\this folder are empty at first

    This is that i will to result after execute the batch file


    But I only have the filelist.txt, this file dont have the relative paths of the files

    Ps sorry for my enligish

    Thanks and regards


  • So it sounds like you want to copy only those files whose names are in the given file list. The easiest way I can think of is by doing this:

    for /f "delims=" %%i in (filelist.txt) do xcopy "c:\Temp\%%i?" "c:\Final" /i /z /y /s

    The two key changes are the question mark at the end of the first path in the xcopy command, and the /s switch.

    By adding a question mark to the end of the first path, you allow xcopy to look for “all files that match the pattern”. Of course, this means that test1.txt and test1.txtt would both match, but since it’s unlikely you have files with more than three characters in the extension, this should be fine.

    The /s switch tells xcopy to search all subdirectories of the source directory for matching files, and copy them to the destination with the same folder hierarchy.

    To test it out, run the following:

    xcopy c:\windows\*.log c:\temp /i /z /y /s

    This will copy every *.log file from the Windows directory to your c:\temp directory. This will result in operations like the following:


    In the temp directory, you’d have this:



  • Manuel

    Hi Brian, thanks for your help. The script its working ok…I´ve an error in the
    sintaxis of the xcopy command…but now is everything OK


  • Manuel

    Hi Brian, a need your help one more time

    Supose that I got a file “filelist.txt” with this content (names without extensions)



    I have a folder with a lot of files named like this form (test.txt, test.xls, test.doc, etc…) see example below



    I need copy all of the contents in the “Temp” folder, to another folder “Final”, with subfolders named like
    the name of files and including the files with same name inside of the several folder see below

    c:\Final\ \\this folder are empty at first or don´t exist at first

    This is that i will to result after execute the batch file




    Ps sorry for my enligish, I hope I had explained correctly

    Thanks and regards


  • Manuel,

    I’d love to help out, but your requests are getting very specialized, and getting close to consulting services. I’ll try to point you in the right direction…

    First, you’re going to need to a combination of a FOR loop to parse the filenames in the text file. Next, you need to create the directory, then copy files to it.

    Try creating a batch file with this:

    for /f "delims=" %%i in (filelist.txt) do (
    md c:\Final\%%i
    xcopy c:\temp\%%i.* c:\Final\%%i /i /z /y /s

    I didn’t test that but it looks right. :)

    If you need further services, you can consider hiring me as a consultant. 😀

  • Josh

    I appear to be having the same issue as Joe.

    Before running this in my live environment, I decided to test it first.

    My bat file states:
    for /f “delims=” %%I in (test.txt) do echo D| xcopy “C:\Documents and Settings\e1000721\Desktop\New\%%I” “C:\Copy\%%I”

    My test.txt file states

    And it does copy over fine, only when it finishes, the file structure appears as

    Any thoughts on how I can get it to not make the last subfolder the name of the file?


  • Try replacing xcopy with a regular copy command — it might do the trick. (For some reason xcopy is defaulting to behavior assuming that the destination is a directory, not a file. Usually this only happens when the /I switch is present.)

  • Josh

    Tried copy and it just bombed out. I then put a pause at the end of the batch file so I could see exactly what it was doing. The issue with the xcopy wound up being that it was set for Directory instead of File so I changed D| to F| before the xcopy thus making the script:

    for /f “delims=” %%I in (test.txt) do echo F| xcopy “C:\Documents and Settings\e1000721\Desktop\New\%%I” “C:\Copy\%%I”

    Thanks again for the great help.

  • Sari

    Thanks Brian! This was exactly what I was trying to do. Years ago I did a lot with DOS batch files and now I can not remember how to do it since dragging and dropping everything.
    I modified your example a bit to create a text file listing files, which were not found.

  • David Lim


    You are a genius! I have been trying to do this all night without success and am glad that I found this site. Thank you!!!

    Keep up the good work.


  • You’ve saved me sooo much time! “Thank You” can’t begin to explain my gratitude. You’re awesome :)

  • Lester


    How I have a problem, the filelist.txt that i’ve created constains different locations (server locations),
    Can this be done using your batch file?


  • If your filelist.txt has the full path to the files, you need to do two things:

    1. Remove any path prefix to the source parameter of the xcopy command.
    2. Remove the first slash in the UNC path in the destination parameter of the xcopy command.

    Fortunately the command shell in Windows allows you to specify a substring of characters from a variable (called string indexing, see If the variable %i was your full UNC path, and you want to drop the first character (so you don’t have a double-slash in your path), you can specify %i:~1 — the :~1 says “start from the second character” (strings are zero-indexed, so the first character is at position 0, the second at position 1, etc.).

    Your command line can then be:

    for /f “delims=” %%i in (filelist.txt) do ( set fil=%%i
    echo D|xcopy “%%i” “c:\temp\%fil:~1%” /i /z /y )

    You have to set a temporary variable (“fil” in the above), since as far as I can tell string indexing doesn’t work with the %%i for loop variable.

  • PatrickMc

    Nice problem and solution. Can a scripting langugage such as biterscripting make the task easy ? Here is a script.

    # Script CopyFiles.txt
    var str src, dest, list, file
    cat “/path/to/list file.txt” > $list
    lex “1” $list > $file
    while ($file “”)
    system copy (“\””+$src+”/”+$file) (“\””+$dest+”/”+$file)
    lex “1” $list > $file

    This script is in biterscripting ( ). Save the script in file C:/Scripts/CopyFiles.txt. Call the script using the following command.

    script “C:/Scripts/CopyFiles.txt” src(“/path/to/source folder”) dest(“/path/to/destination folder”)

  • Adrian

    Thank you very much for such a useful script, i’ve been looking for it for 2 days, but i have a problem

    in my filelist.txt i have listed a lot of files with special characters, like á é í ó ú so it keeps telling

    me file not found because it cannot read any of those characters, is there any way to fix this problem?

    i really need to get over this, i have like 10 files listing me 200 files each one, it would take me

    years to do it manually :S

  • Gayatri Prabakar

    Thanks a lot, brian!!! :)

  • Sony

    Hi Brian,
    I need ur help very urgently.

    I have a text file which contains list of folders and files I want to copy to another location. Those folders r in different drives like C: and D:.
    My text file content gos something like this.

    Can u please give me the script that copies these folders along with their subfolders and contents to another location??

    I have tried many. One of those is :
    for /f “delims=” %i in (D:\includelist.txt) do xcopy “%i\” “U:\BACKUP\” /i /z /y /s /e

  • First, I would specify U:\BACKUP\%i
    Second, if you are running the script from the command line, you need to double the percent signs.
    Third, if some of the source files are folders, and some are files, you need to be careful with your backslashes.
    Fourth, what error are you getting?

    Try this:
    for /f “delims=” %%i in (D:\includelist.txt) do xcopy “%%i” “U:\BACKUP\%%i” /i /z /y /s /e

    • Sony

      The script that u mentioned copies only subfolders. My includelist is something like this :

      When i run the script it copies only Test and Test1 in U:\BackUp. The Entire folder structure is not created. Please help me with this.
      I tried the following : for /f “delims=” %i in (D:\includelist.txt) do echo D|xcopy “D:\%i” “U:\BACKUP\%i:~1%” /i /z /y. This works well.
      But this has D:\ in the source. I do not want that. I read the complete path in %%i.

  • Damian Stalls

    This is AWESOME!! But I am having a similar problem as Sony. My list.txt file contains the full source path (as there could be multiple drive sources). Is there a way to make the destination of the batch file ignore the drive letter for the destination?

    c:\users\damian.home\appdata\local\microsoft\outlook\MailStore Offline.pst

    for /f “delims=” %%i in (filelist.txt) do echo D|xcopy “%%i” “D:\PSTs\%%i” /i /z /y

    The source works fine but the destination tries to copy to “D:\PST\C:\USERS…”. Actually if the destination could just drop the “:” that would be PERFECT!

    • Damian Stalls

      Nevermind… i finally figured it out. The example you provided needed some extra quotes when setting the fil variable, and the substrings needed to be updated:

      for /f “delims=” %%i in (filelist.txt) do ( set “fil=%%i”
      echo D|xcopy “%%i” “D:\DESTINATION\%fil:~0,1%%fil:~2%” /i /z /y )

      This copy the source file as follows:
      C:\Folder1\file.nam –> D:\DESTINATION\C\Folder1\file.nam
      E:\Folder3\file1.nam –> D:\DESTINATION\E\Folder3\file1.nam


      • Sony

        Heyy Damian,

        I tried ur script. But it doesnt work. it created a folder named “~0,1%fil” in U:\Backup. It copied only 2 files from the entire folder.

        I just need to truncate the drive D:\ name from destination path. Can u please look into that?

  • Damian Stalls

    Spoke too soon… if you execute the batch file from a command line it works. If you double click on the batch file it does not! Any ideas?

  • W Noel

    Hey Brian,

    Thanks for such amazing information!

    I want to create the scenario Manuel was asking about:

    Some files are in multiple SubDirectories and I have the file names in a text file (file1.pdf file2.pdf file3.pdf)

    I want all locations of the same file recreated when applicable.





    …Where file3.pdf was found in two locations and placed in both trees.

    So far, I keep getting a directory created with the file name like follows:


    …Where fileX.pdf folders are created and file3.pdf is in its appropriate tree but both under a file3.pdf subdirectory and

    I’ve tried:

    do echo D|xcopy
    do echo F|xcopy
    do xcopy

    and I’m not getting the result I want yet.

    I hope that all makes sense : )

    Any thoughts?

    Thanks, Brian!

  • vinny

    set src_folder=C:\Users\Vinny\Desktop\Scorpio\Catalog 2013
    set dst_folder=C:\Users\Vinny\Desktop\Scorpio\Catalog 2013\catalogimages\
    for /f “delims=” %%i in (filelist.txt) do echo D|xcopy “C:\Users\Vinny\Desktop\Scorpio\Catalog 2013\%%i” “C:\Users\Vinny\Desktop\Scorpio\Catalog 2013\catalogimages\%%i” /i /z /y

    i am using this and its putting the images into folders inside the catalog images folder i cannot figure out why. someone had this issue further up but didnt reply with his fix.

  • You for command looks fine (and the set command aren’t needed as you are not using the variables you are setting).

    I just tried this by doing the following:

    Batch file:
    for /f “delims=” %%i in (c:\temp\filelist.txt) do echo D|xcopy “C:\temp\%%i” “C:\temp\output\%%i” /i /z /y

    FileList.txt file:

    The result was the restoredb.bat and restoredb.sql files, both of which originally existed in the source folder (c:\temp), were copied to the destination folder (c:\temp\output).

  • vinny

    ok i dont know anything about this stuff. so i guess i have to find a completely new way to do this because this command is not working. i cant have all of them moved into there own folders and thats whats happening.

  • vinny

    for /f “delims=” %%i in (filelist.txt) do echo D|xcopy “C:\Users\Vinny\Desktop\Scorpio\Catalog 2013\%%i” “C:\Users\Vinny\Desktop\Scorpio\Catalog 2013\catalogimages” /i /z /y

    thats what did the trick

  • Bal

    My filelist.txt has a list of files that are seperated into sections.

    filelist.txt e.g.
    Section 1

    section 2

    Is there a way to only copy the files in section 2?

    this is the command I am using but it copies all the files in listed in filelist.txt

    for /f “delims=” %%i in (filelist.txt) do echo D|xcopy “C:\test\%%i” “C:\test2” /i /z /y
    Pls can you help?

  • Mike

    What if I just want to copy the files in the filelist.txt source into a single destination directory, ignoring what subfolders they originated in?

  • @Mike — the easiest way to do this is, assuming your filelist.txt has a list of files with path names:

    for /f “delims=” %%i in (c:\temp\filelist.txt) do echo D|xcopy “%%i” “C:\temp\output\%%i%~nxf” /i /z /y

    That may work, I didn’t try it. The tilde in the variable is part of ‘variable substitution’ in the command shell. See

  • Alex

    Hi Brian,

    Can you please guide me for the below query –

    I want to move files from one folder location to a temp location with conditions as below
    1) All the files lesses than sysdate
    2. After files are copied to temp location it should be zipped.
    3. Again I have to copy these zip file to a different location and than unzip it.

    Please help … Appreciate ur swift response!


  • Kirke

    Hi Brain,

    Are you getting payed for all this work?
    I just read through the whole tread, and it seems you are the only contributer to actual solutions…..

    What I read is very usfull, but I can’t figure out how to seach the files from the list in subfolders.
    Is this even possible?

    I used this:

    For /f “delims=” %%i in (filelist.txt) do xcopy “c:\Temp\%%i?” “c:\Final” /i /z /y /s

    and it woorks great if all files are located in c:\temp\

    But the files I am looking for is in subfolders to c:\temp\

    Hope you yet again can come with a solution :-)

    Best regards

  • Kirke

    jesus just tried it out another time and it works… really are the man Brain, you should get payed for this….

  • @Kirke — thanks for the kudos, and glad you got it working. Batch files are a labor of love… :)

  • Adeya

    Hello, Brian!
    1. I’m beginner. Though cases discussed on your site are very similar to that what I need, still I can’t get the solution.
    2. My case:
    2.1. I have a folder C:\temp with, say, 3 Excel files Name1.xlsx, Name2.xlsx, Name3.xlsx
    2.2. I have FileList.txt file in C:\temp folder. File contains:
    2.3. I need to move files Name2.xlsx and Name3.xlsx, as defined in FileList.txt, from the folder C:\temp into the folder C:\temp\new

    PS. An advantage of vehicle with manual gear compare to the one with automatic is that in case of manual gear I can start the engine from the push. I am looking you to push me. Thank You.

  • Adeya

    My OS is WINDOWS 7.

  • Use the same command line, just change the source path and use MOVE instead of XCOPY.

    for /f “delims=” %i in (filelist.txt) do move /y “c:\temp\%i” “c:\temp\new\%i”

    Important note — if you put this in a batch file, you need to use %%i; if you run it directly from a command prompt, you use %i.

  • Adeya

    This batch file:
    for /f “delims=” %%i in (C:\temp_ad\filelist.txt) do echo D|xcopy “C:\temp_ad\%%i” “C:\temp_ad\output\%%i” /i /z /y

    works neither in Win XP nor WINDOWS 7. Folder \output\ remains empty.
    Batch file resides in temp_ad folder.
    filelist.txt looks as follows:
    Hope on your help.

  • What is the output when you run just this from the console (not a batch file)?

    for /f "delims=" %i in (C:\temp_ad\filelist.txt) do echo xcopy "C:\temp_ad\%i" "C:\temp_ad\output\%i" /i /z /y

    Remember to make quotes normal quotes; I think WordPress is replacing them with curly quotes when the comment is posed.

  • Adeya

    The problem was the quotes: they were not normal.

    Here is working version.

    cd C:\temp_ad
    for /f “delims=” %%i in (filelist.txt) do move /y “C:\temp_ad\%%i” “C:\temp_ad\output\%%i”

    Brian, you gave me a push, thank You, though I am not sure how long my ‘engine’ will work, maybe I will need another push:) Thanks a lot.

    Another small question: is it possible to WinZip the files? I wrote batch to unzip it, but how to zip?
    Highly appreciate your help.
    Thank you.

  • @Adeya — funny you ask about zipping the files, I recently wrote a batch file to zip (using 7zip) a folder. Expect a blog post soon.

  • andy

    Hi Brian!

    i’m in need of a little help here please, been going round and round with this to no avail!! :(

    The goal of this batch is to copy files from a server to a local PC, scheduled to run every 30 minutes, to copy each project’s image folder and copy to a local PC.

    I have a set of text files, all with random names i.e. 154799.txt in a single folder, the contents of each file is a single line with a UNC path \\server_name\folder\user\jobname (each of these paths contain image files)
    I need to use the contents of each text file as a path for a robocopy command
    There is an unknown number of *.txt files each with random name, so this needs to run once for each ‘new’ textfile.

    I have this batch that generates a list of the filenames and outputs into a single text file called files_list.txt file

    for %%a in (*.txt) do echo %%a >> \\server_name\folder\user\file_list\files_list.txt

    for /F “tokens=*” %%g in (files_list.txt) DO @echo %%g

    That produces a file_list.txt with contents:

    Where I’m stumped is getting the next batch to take each line of the files_list.txt as a source path

    for /f “delims=” %%i in (file_list.txt) do robocopy “%%i” c:\copy\server_footage\ /s /e

    Any help greatly appreciated! Thanks, Andy!

  • andy

    last line has a typo it should be files_list.txt not file_list.txt!
    for /f “delims=” %%i in (files_list.txt) do robocopy “%%i” c:\copy\server_footage\ /s /e

  • Two things that could be throwing you off:

    1. Use “delims= ” — that is, use a space as a delimiter. This solved a problem for me in eliminating white space at the end of the filename.

    2. You need three loops. Think of it this way:

    LOOP 1 — get the filename of all text files (*.txt) and put it in a new file (files_list.txt)
    LOOP 2 — go through files_list.txt, and for each line (i.e. each file, do LOOP 3
    LOOP 3 — called by loop 2, this reads each line in the file and does the robocopy

    Your LOOP2 and LOOP3 have to be in the same command, something like this:

    for /f “delims= ” %%i in (c:\temp\files_list.txt) do for /f “delims= ” %%j in (%i) do robocopy “%%j” c:\temp
    \destination\ /s /e

    Hope that helps!

  • andy

    Yep, that’s got it! the for / do needed to be in the same command!

    Thanks Brian! :)

    • andy

      Hi Brian,

      I have another change I would like to implement:
      Deleting the 154799.txt file if there is no new data (changes/updated/new files) within the source folder

      using the errorlevel check from Robocopy
      errorlevel 0 echo No Change & goto remove
      remove then deletes 154799.txt and all other *.txt files but I can’t seem to find a way to split this out of the original variable in Loop 3.
      It acts only on the last *.txt file it reads, so if there is no change to that, it deletes all *.txt, even if the preceding files had new or changed content.

      Section of script contains:

      goto :EOF


      if errorlevel 16 echo ***FATAL ERROR*** & goto end
      if errorlevel 15 echo OKCOPY + FAIL + MISMATCHES + XTRA & goto end
      if errorlevel 14 echo FAIL + MISMATCHES + XTRA & goto end
      if errorlevel 13 echo OKCOPY + FAIL + MISMATCHES & goto end
      if errorlevel 12 echo FAIL + MISMATCHES& goto end
      if errorlevel 11 echo OKCOPY + FAIL + XTRA & goto end
      if errorlevel 10 echo FAIL + XTRA & goto end
      if errorlevel 9 echo OKCOPY + FAIL & goto end
      if errorlevel 8 echo FAIL & goto end
      if errorlevel 7 echo OKCOPY + MISMATCHES + XTRA & goto end
      if errorlevel 6 echo MISMATCHES + XTRA & goto end
      if errorlevel 5 echo OKCOPY + MISMATCHES & goto end
      if errorlevel 4 echo MISMATCHES & goto end
      if errorlevel 3 echo OKCOPY + XTRA & goto end
      if errorlevel 2 echo XTRA & goto end
      if errorlevel 1 echo OKCOPY & goto end
      if errorlevel 0 echo No Change & goto remove

      for /f %%a in (\\server_name\folder\copy_dir\file_list\job_list.txt) do del %%a

      Any suggestions please? Thanks!

  • Adeya

    Hello, Brian!

    By executing the batch I started to get prompt:
    “Does C:\temp_ad\output\test2.xlsx specify a file name or directory name on the target
    <F = file, D = directory)?"

    I think it started after MS Office 2013 was installed. My OS is WINDOWS 7.

    How to prevent this prompt or how to select 'F' automatically?

    Thank you.

  • Can you send me the command that your batch file is generating that is causing this error?

  • Adeya

    for /f “delims=” %%i in (filelist.txt) do xcopy “C:\Test1\%%i” “C:\Test1\Test2\%%i”

    Batch file itself and filelist.txt are in Test1 folder along with files .xlsx that are copied from Test1 into Test2.
    Prompt forces to enter ‘F’ as many times as number of files to be copied.

    Thank you for your time.

  • Try using the XCOPY command line switches /I /Y.

    for /f “delims=” %%i in (filelist.txt) do xcopy “C:\Test1\%%i” “C:\Test1\Test2\%%i” /I /Y

  • Adeya


    xcopy switch /I says: “If destination does not exist and copying more than one file, assumes that destination must be a directory.”

    So, the prompt is displaying no matter destination exists or not, copying one file or more.

    xcopy switch /Y says: “Suppresses prompting to confirm you want to overwrite an existing destination file.”

    So, by first run switch /Y does not help: prompt requiring ‘F’ or ‘D’ is displayed.
    If files are already copied into destination file, then by the second run neither the prompt in question nor the confirmation overwriting prompt are displayed.

    I experimented with Win XP & MS Office 2007, Win XP & MS Office 2010, and Windows 7 & MS Office 2013. The behavior in all cases are the same: prompt is displayed.
    I was absolutely surprised to see it on my Win XP machines. Since April 30 (see my msg above) I was occupied with other assignments, I new that batch exists and did not try it until recently.
    I think this prompt is caused by some updates that change some security settings. I googled and people mention it, too.
    Maybe you can figure this out.
    Thank you.

  • Adeya

    If destination folder is created before batch execution, than prompt has preceding phrase:
    “A subdirectory or file Test2 already exists.” and further the known question ‘F’ or ‘D’.
    Thanks a lot.

  • Marcos

    Hi brian, great job.

    I have this issue, i wonder if you could help me out..

    I have several pdf files that i need to relocate, the list.txt has the directory names of the location of the pdf files.

    What i need is that the command use the list.txt where the locations of the files are…

    I apologize for my bad english… and thanks in advance



    This coommand works for what i need to do

    for /R f:\temp\folder1 %f in (*.pdf) do copy %f F:\temp\folder1 /y

  • Adeya

    Hello, Brian!
    Googling brought the solution. Though this solution is not universal, but for my case it is the solution.
    If by copying the file name is not changing (what is my case), then there is no need to provide file name at destination (in my case %%i at the end of the destination path can be skipped) and “Does C:\… specify a file name or directory name on the target
    <F = file, D = directory)?" prompt will not displayed.
    So, my command will look as follows:
    for /f “delims=” %%i in (filelist.txt) do xcopy “C:\Test1\%%i” “C:\Test1\Test2\”
    Thank you.

  • @Marcos — if your list file has folders and not files, you can do something like this:

    for /f "delims=" %%i in (filelist.txt) do xcopy "%%i" "c:\temp\destination\" /s /i /z /y

    • Marcos

      Hi brian, thanks for the answer, perhaps, i failed on the explanation of my problem.

      I have several pdf files on subfolders, and I need to move these files to an upper level directory. for example

      I have

      And I need:

      I Have this list.txt where i have all the folders listed


      So long, i´ve managed that the script “reads” all directory but it wont copy

      If I do This

      for /R C:\FolderA %f in (*.pdf) do copy %f c:\FolderA\ /y

      The Result is what i Expect, al pdf files in c:\FolderA , and it’s subfolders copies to the directory c:\FolderA

      But if i do this

      for /f “delims=” %i in (list.txt) do echo D|for /R “c:\%i” %f in (*.pdf) do copy %f “c:\%i\” /y

      The script “reads” all directory but it wont copy any files

      • @Marcos — in the second FOR loop, don’t re-use %i, try a different letter (%q).

        • Nikos

          Hello Brian,

          Thanks for all these posts here. I have a similar problem I have a folder with all the files there and need to split them in different folders and subfolders

          So in the destination I want to create also the folders like:


          Can you please help me?


  • Alex David

    I have two logs called chknew.log and new.log
    chknew.log contains the source filepath as C:\ILProject\DateFormat.vb

    new.log contains the destination file path as C:\ILProject\BUILD_MANDATORY\DateFormat.vb

    I want to xcopy files in log please help

    • I’m assuming that each line in chknew.log (source) has a corresponding line in new.log (destination), so each row matches in each file… If that’s the case, let me think… you can loop through one file but not two files.

      This was a cool one, worthy of its own blog post… but in short:



      Batch file to copy files where the source is the value in source.txt and the destination is the value in dest.txt:

      @echo off
      set /a line=0
      set dest=
      for /f %%i in (source.txt) do (
      call :getdest !line!
      set /a “line+=1″
      echo %%i, !dest!
      goto :eof

      if “%1″==”0″ (
      for /f %%j in (dest.txt) do (
      set dest=%%j
      exit /b
      for /f “skip=%1″ %%j in (dest.txt) do (
      set dest=%%j
      exit /b

  • Kal

    I have two directory on my D Drive. D:\1 and D:\2 Directory 1 and 2 and subdirectories have a bunch of files .

    I need a batch script that will Read each file in Directory 1 and checks, if same file exists in Directory 2, it should avoid duplicates files. Move only those files which are not present in directories 2 to a different Directory C:\3 with the same folder sturcture.

    Thanks in advance

  • @Kal — I would recommend using a tool such as WinMerge, which can compare folders of files, show you what’s the same, different, and missing on one side or the other, and move them accordingly. It’s a great tool, and it’s free.

  • Kal

    Thanks Brian. I have already tried that!!! But no success as the folder structure are diff on both Directories. I required script that search for file in A and B folders and compare the filename if same file exist on both folder it should avoid it. If Unique file exist on Dir A it should copy the file with same folder structure of DirA to DirC.

    Thanks in advance.

  • Kal

    Hi Brian;

    I am using below script for the above requirement, but no success.
    @echo off
    set d1=”D:\Login\*”
    set d2=”D:\LOGIN2\*”
    set dest=”D:\RESULT”
    for %%f in (%d1%\*) DO (
    if not exist %d2% move %%f %dest%


  • Alex David

    Thanks for your solution but its not working…please do needful help

  • Alex David

    Hi Brian,

    I want to delimit this statement $/MIGRATION_UAT/Integration/NSureIntegration/NSure_event1/dbutility/BIN/Interop.MSXML2.dll

    as \\\c$\inetpub\wwwroot\NSureIntegration\NSure_event1\dbutility\BIN\Interop.MSXML2.dll
    using batch script

  • Alex

    I have a list(“MissPDF.txt”) that contains path and file name like below:
    EDI 2011 – 1\184160184160594.pdf
    EDI 2011 – 3b\184497184497738.pdf
    EDI 2011 – 3b\184497184497739.pdf
    EDI 2011 – 3e – Copy\184473184473289.pdf

    I want to copy those files to this location:

    I tried creating this line of code but it is not working for me, can you help?

    for /f “delims=” %%i in (MissPDF.txt) do echo D|xcopy “E:\PRGX\Data\Carrefour\%%i” “E:\PRGX\Data\MissedPDF\%%i” /i /z /y /s

    I put the bat file and misspdf.txt in this directory:

  • Alex

    The text file has this data. There was a slash missing on my example earlier

    EDI 2011 – 1\184160184160594.pdf
    EDI 2011 – 2c\184307184307471.pdf
    EDI 2011 – 3b\184531184531849.pdf

  • Alex

    There should be a slash after the 6th number in hte pdf file name. ie 184160 “\” 184160594. for some reason it disappears when I post this msg.

    EDI 2011 – 1\184160184160594.pdf
    should be:
    EDI 2011 – 1\184160 “\” 184160594.pdf (witohout the quotes and space)

  • When I copied your text into a sample file, the following from a command line works fine. I think you need to better explain what “it is not working for me” means.

    for /f “delims=” %i in (c:\temp\MissPDF.txt) do echo xcopy “e:\prgx\data\carrefour\%i” “e:\prgx\data\missedpdf\%i” /i /z /y /s

  • Alex

    The files are not being copied I right click on my bat file and click open and it opens and closes right away…nothing happens. Could it be the spaces in the directory name “EDI 2011 – 1…” ?

  • Alex

    This is the full path of the first file in my example (184160184160594.pdf)
    E:\PRGX\Data\Carrefour\EDI 2011 – 1\184160\184160\184160594.pdf

    The MissPDF.txt file has this on the first line:
    EDI 2011 – 1\184160\184160594.pdf

  • Alex

    I found the issue. I had these double quotes (”) instead of (“). Once i changed it, it started working, kinda. Now I get an error msg for each file asking to specify if a file name or directory name on the target <F = file, D = Directory)? D 0 File(s) Copied

    what to do?

  • Alex

    for /f “delims=” %%i in (MissPDF.txt) do echo D|xcopy “E:\PRGX\Data\Carrefour\%%i” “E:\PRGX\Data\MissedPDF\%%i” /I /Z /Y /S

    This worked. Just needed the \ at the end of the destination

  • Alex

    Only thing is it is creating the file in a folder with the file name. how do I prevent it from doing that?

  • You have backslashes in the file names in your text file. This will cause problems with file copies, as Windows will think it’s a directory path. Try replacing the slashes with a valid character (dash or space).

  • Alex

    The files are in different subfolders…that’s why I have the backslashes.

  • You should use the various “tilde” functions to transform a full path to a file to just the file name, to avoid the source having a full path and the destination using just the file name. See

  • Alex

    ok..started over and I put all my pdf’s in 1 folder (E:\PRGX\Data\Miss2Left)
    I have a text file called Miss2.txt which has the file names in it

    I want to copy the files from Miss2Left folder that exist in the text file to this folder (E:\PRGX\Data\Miss3Left). I have this command that works but that creates a folder with the filename and then the file inside that folder:

    for /f “delims=” %%i in (Miss2.txt) do echo D|xcopy “E:\PRGX\Data\Miss2Left\%%i” “E:\PRGX\Data\Miss3Left\%%i” /i /z /y

    What am I missing?

  • Try taking out the /i switch. Or, to debug the copy command, use the /l switch to see what would happen without actually doing the file copies.

  • Alex

    I got it to work but it is going very slow. I am putting it into an “ALL” folder. There are about a million pdf files and about 120,000 file names in Miss2.txt file. It is copying about 10 files a minute.

    for /f “delims=” %%i in (Miss2.txt) do echo D|xcopy “E:\PRGX\Data\Miss2Left\%%i” “E:\PRGX\Data\Miss3Left\%i:All%” /i /z /y

    I was experimenting with this below. Would something like this go faster? If so, what would i need to edit below? It is not copying the files.

    for /f “tokens=*” %%A in (Miss3Path.txt) DO (If Exist %%A* (XCOPY “%%A\*.pdf” “E:\PRGX\Data\Miss4Left” /D /K /Y /R ) )

  • Alex

    FYI…the Miss3path.txt file has this data in it:

  • Do you have “about a million pdf files” all in the same folder in the source? If so, I’d say that is part of your problem. I’ve seen Windows have problems with folders of 10,000 or more files. A million is a LOT of files, much less all in the same directory.

  • Paul

    Why am I getting the error?

    for /f “delims=” %%i in (filelist.txt) do copy “%%i” “”c:\folder1\%%i”
    ” was unexpected at this time.

  • Tristen

    As an extension, how would you go about copying a group of files listed in “FILEPATH_FROM.CSV” to the location in the corresponding “FILEPATH_TO.CSV”? e.g the ith line of both files correspond to the from and to arguments of xcopy respectively.

  • Tristen

    Sorry, I now see the question had been asked, my mistake.

  • Art


    The batch file works fine, is it possible to make it generate a list (txt) file of the ones that it couldn’t find?

  • leslie

    Using the FOR command to delete files listed in a text file from a specific directory?

    for /f “delims=” %%i in (imagelist.txt) do echo D|del “\\c:\imagestore\%%i” /i

    nothing happens, help?

  • sourabh

    You can use the following command in case you are stuck with folders getting created with file name:
    for /f “delims=” %%i in (filelist.txt) do echo F|xcopy “\\server\share\folder\%%i” “c:\temp\%%i” /i /z /y

    the key here is to tell cmd that destination is a file instead of a directory.

  • Nikos

    Hello Brian,

    I have a folder with files that I do need to copy to multiple folders and subfolders. The folders and subfolders are not created but have them in txt list together with the name of the specific file.

    For example I want to move

    test1.txt to folder1/subfolder1 test2.doc to folder1/subfolder2 test3.txt to folder2/subfolder1 …………..
    • test1.txt to folder1/subfolder1
    • test2.doc to folder1/subfolder2
    • test3.txt to folder2/subfolder1

    Can I do it in from command line copying the files and creating the folders at same time if I have each destination path in a text list?

  • Nikos

    I have a folder with files that I do need to copy in multiple folders and subfolders. The folders and subfolders are not created.

    For example I want to move

    • test1.txt to folder1/subfolder1
    • test2.doc to folder1/subfolder2
    • test3.txt to folder2/subfolder1

    Can I do it in from command line copying the files and creating the folders at same time if I have each destination path in a text list?

  • Dei Wills

    Hello Brian.

    I am very new to this forum and process. I am trying to create a batch file that will move employee files into it’s own employee folder. For example…

    move from – O:\Payroll\Exempt Time Off\2014\1 Extract\Andersen Julie -TAFW 07.31.14 19.pdf
    move to – O:\Payroll\Exempt Time Off\2014\Andersen Julie

    Is there a way to do this, as it is for multiple employees?

    Thanks for kindly.

  • the first *.tif file is being dropped and not copied to new folder? Does anyone know why?

    for /f “delims=” %%i in (CD200.txt) do echo f|xcopy “X:\oldCDFolder\CD200\%%i” “X:\newCDfolder\CD200\%%i” /i /z/y/f

    CD200.txt contains:

  • Ryan


    Thanks so much for this. I realize it is an old post but I have a question regarding my results. Here is what I’m running:

    for /f “delims=” %%I in (TEST.txt) do echo F| xcopy “Source\%%I” “Destination\%%I”

    I ran 28,000 files from various folders/levels of folders and it worked great (27990 files copied)! However, about 50 seemingly random files do not get moved and result in a “0 File(s) copied” message.

    I can see nothing odd about the files that are not getting copied. For example, one folder contains 100 .tif images, all filenames are numbers in ascending order. Only 2 of the images were copied. If I alter my TEST.txt and only run a subset of those 100 through (10 say), DIFFERENT images get copied/don’t get copied.

    Any reason it’s randomly not copying certain files? If not, no worries and thanks for the batch file!

  • Ryan

    I’m thinking maybe my TEST.txt file contains hidden characters or something. I guess I’ll have to clean it somehow.

  • prakash

    Hi Brain

    I have used this script to copy files , but found some files got skipped , is it possible to create an log of skipped files.

  • Zach

    I’m getting “xxi was unexpected at this time.” Thoughts?

  • Andrea

    Hi guys,

    i’m sorry for my english.
    how can i edit the file batch so that it gives me a final result??
    For example, i have this list with 250 files and i want to know, in a new txt file if some of this aren’t copied.

    thanks to all

  • Chintan

    I am not programming guy but you made it so simple it saved me hours….Thanks a heaps

  • mansh

    how can i open one new excel sheet inside which is located folder in desktop using with cmd prompt.

  • […] I had a unique request to copy a list of folders out of a greater collection of folders. Seeking the best way to do this I found this solution thanks to sidesofmarch: […]

  • Ashik

    Hi Brian,
    I need to copy the content of muiltiple files in one file
    e.g file1.txt+file2.txt+file3.txt to filex.txt

    I use the copy command to do that, but the beginning content of file2 is being copy on the same end of line of file1.txt and file3 being copy the end of file2.txt
    There is an overlapping at the end of each file.
    All i need is the all the 3 files to be copied into one file named filesx.txt

    Thanking you in advance for your support


  • @Ashik — sounds like you need to add a line break between files.

    Create a file, break.txt, with its only content being a blank line (i.e. open notepad, press enter, save file). Copy this file between the other file copies when appending files together and it will ensure a line break between files.

  • Tom

    Hi Brain,

    No sure if you can help, I’m trying to write a copy script that will search multiple directories on a network share for specific file names that are listed in a text file, then move them into a new folder, doesn’t need to keep folder structure in destination folder. I want to dump it all in one folder




    Thanks For any info you cna provide

  • Tom

    So this is what I have, but it doesn’t seem to even search sub-directories for the files so my output is,
    The system cannot find the file specified.
    0 file(s) copied.

    I know the files are there just within sub-folders

    for /f “delims=” %%i in (filelist.txt) do (
    copy /y “F:\network_sahre\%%i*” “F:\network_share\Temp”

  • @Tom, In your COPY command, try including the /s switch to also search sub-directories.

  • Robert

    Brian, You have got me on the right path. However, I’d like to delete the source files after they have been copied leaving the source folders intact because they have other files in them. Thanks

    Your code I used.

    for /f “delims=” %%i in (list.txt) do xcopy “C:\Users\BEAZLEYBUB\Desktop\New folder\New folder\%%i?” “C:\Users\BEAZLEYBUB\Desktop\New folder\Copied” /i /z /y /s

  • @Robert — easiest thing is to use the ROBOCOPY command instead of XCOPY, and use the /mov (move) switch, which moves files instead of copying them.

  • Joop

    Hi all,

    I want to do the following thing:

    I have an output of a DIR search result on a specific term “test” on volume c: in a text file, eg


    I want to use this text file to make robocopy copy these folders and content to another drive/volume.
    I want to keep the exact folder structure in the destination drive, eg f:


    I tried the For \f “delims=” %%I to read the strings of the text file and use the %%I as source for robocopy, but how can i make a destination path in the same way? I cannot use %%I for that, as the driveletter (c:\) is wrong in that case.

    Leave the destination empty results in


    (Without the root directories)

    Any suggestion?


    (Sorry for my bad English)

  • B.Ng

    Hi Brian,

    Great work with this blog.

    I had a quick question – probably the easiest one you’ve had to deal with. I’m new to scripting and I’m attempting to copy files with the contents “Parker” from a specific to another folder. The files have different extensions and identical file-names.

    For example:


    When I run the below script, only one of the pdfs is copied to the folder. I want where it copies all the pdfs. I’ve checked these pdfs and they do indeed have the content “Parker.” How would you adjust this script?

    for /f “delims=” %%a in (‘findstr /m /c:”Parker” *.*’) do echo F|xcopy “%%~Na.*” “C:\Test” /i /z /y

    Thanks in advance

  • manu

    i would like to copy a folder on my c drive to a set of PC’s on the network

    PC names are in a txt file

    Please help


  • killean

    does anyone know how to Create a batch file that automatically backups the users document folders. It needs to check if files exist in the destination, copy only files that have changed since the last time it was ran. It will need to create any files or folders that are new since last backup. When started it should ask the user for their full name, user name, to close all files and folders, and ask if it is ok to proceed with back up. The files should back up to the users H: drive into a folder called backup. The backup directory will then be compressed to save space. A log should be updated when ever the batch file is used, logging employee name, user name, time, and date.

  • dwarka

    hi all i required a batch file which copy folder & subfolders from clinet node to server/ How batch file will take ip address of all lan pcs pls guide or give me a single example for batch file

  • donechild

    please can anyone help me with this batch file but its in dutch
    the idear was to make a search batch file and than at the end of the search, the batch file should prompt and ask do you wanna save the results to notepad , if yes then its will copy all the results into notepad and than it will allow you to save it where you want . but i cant figure out the code to call the notepad and the code for copying result anyhelp?

    echo off
    title zoekopalles
    color 9f

    echo %TIME% %Date%
    echo Halo %username%
    echo Welkome
    echo Gelieve uw voornaam in te vullen:
    set /p fnaam=
    echo Hallo leuk om jou te ontmoeten %fnaam%!

    Title Het Menu
    echo %TIME% %DATE%
    echo Maak Uw Keuzen
    echo 1- PDF Bestanden
    echo 2- Word Bestanden
    echo 3- Opnieuw Starten
    echo 4- Informatie over uw Dir
    echo 5- File Tree


    choice /c:12345
    IF ERRORLEVEL 4 GOTO informatieoveruwdir
    IF ERRORLEVEL 2 GOTO WordBestanden

    dir c:\*.pdf /s

    @echo off
    echo even wachten………..
    dir >> myfile.text

    dir c:\*.doc /s
    dir c:\*.xls /s
    echo. Laad uw resultaat naar NotePad? J/N
    set /p ask=
    if %ask% == J goto NotePad
    if %ask% == j goto NotePad
    if %ask% == N goto START
    if %ask% == n goto START
    dir %file%



    dir c:\windows
    echo start

    tree C:/
    ping localhost -n 5 >nul
    echo start

    :search text.

    Title …even Wachten…
    echo …even wachten…
    goto Start

  • donechild

    the input and the output has to come where the notepad and pause>nul

  • Jhoy

    Hi brian,

    I need help, I need to copy specific files in a zip file and zip the copied files into another zip file.

    i have multiple zip files with file name like – Axxxxmmdd.ZIP where xxxxmmdd varies depending on date. The zip contains files such as A.txt, B.txt, TD-yyyymmdd.xxxx, TH-yyyymmdd.xxxx where yyyymmdd is the date and xxxx varies depending on the number say from 0001. I need to copy TD-yyyymmdd.xxxx and TH-yyyymmdd.xxxx and zip to another zip with filename same as the TH-yyyymmdd.xxxx. After zipping the two files, I have to send it automatically to the network’s shared folder through ftp, like \\\folder

    I am not really familiar with batch file. Your help is highly appreciated and hope to hear from you soon :)

  • Jolly

    Hi All,
    Could you please help me with a Script.
    My Requirement is to check all Log Files in a location and search for a Pattern in the Files.
    If that Pattern is identified then I need to Output that Pattern into another File and display that file in the Browser.
    I have already tried few examples but I am not able to retrive the Pattern into a new File !!

    my script is :

    $Path1 = “D:\ABC\*.log”
    $Text = “*Error*”
    $Path3 = “D:\ABC\t1.html”

    $Content = Get-Content $Path1

    $Content | Foreach {
    if ($_ -ilike $Text)
    {Write-Output $_}
    }| ConvertTo-HTML | Out-File $Path3

    Appreciate a Quick Response !


Leave a Reply




You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>