Windows bat file copy folder

batch/bat to copy folder and content at once

I’m writing a batch script that does a copy. I want to script it to copy an entire folder. When I want to copy a single file, I do this

If I have a folder with this structure, is there a command to copy this entire folder with its contents all at once while preserving the exact structure.

5 Answers 5

if you have xcopy , you can use the /E param, which will copy directories and subdirectories and the files within them, including maintaining the directory structure for empty directories

xcopy is deprecated. Robocopy replaces Xcopy. It comes with Windows 8, 8.1 and 10.

robocopy has several advantages:

  • copy paths exceeding 259 characters
  • multithreaded copying

I suspect that the xcopy command is the magic bullet you’re looking for.

It can copy files, directories, and even entire drives while preserving the original directory hierarchy. There are also a handful of additional options available, compared to the basic copy command.

If your batch file only needs to run on Windows Vista or later, you can use robocopy instead, which is an even more powerful tool than xcopy , and is now built into the operating system. It’s documentation is available here.

I’ve been interested in the original question here and related ones.

For an answer, this week I did some experiments with XCOPY.

To help answer the original question, here I post the results of my experiments.

I did the experiments on Windows 7 64 bit Professional SP1 with the copy of XCOPY that came with the operating system.

For the experiments, I wrote some code in the scripting language Open Object Rexx and the editor macro language Kexx with the text editor KEdit.

XCOPY was called from the Rexx code. The Kexx code edited the screen output of XCOPY to focus on the crucial results.

The experiments all had to do with using XCOPY to copy one directory with several files and subdirectories.

The experiments consisted of 10 cases. Each case adjusted the arguments to XCOPY and called XCOPY once. All 10 cases were attempting to do the same copying operation.

Here are the main results:

(1) Of the 10 cases, only three did copying. The other 7 cases right away, just from processing the arguments to XCOPY, gave error messages, e.g.,

with no files copied.

Of the three cases that did copying, they all did the same copying, that is, gave the same results.

(2) If want to copy a directory X and all the files and directories in directory X, in the hierarchical file system tree rooted at directory X, then apparently XCOPY — and this appears to be much of the original question — just will NOT do that.

One consequence is that if using XCOPY to copy directory X and its contents, then CAN copy the contents but CANNOT copy the directory X itself; thus, lose the time-date stamp on directory X, its archive bit, data on ownership, attributes, etc.

Of course if directory X is a subdirectory of directory Y, an XCOPY of Y will copy all of the contents of directory Y WITH directory X. So in this way can get a copy of directory X. However, the copy of directory X will have its time-date stamp of the time of the run of XCOPY and NOT the time-date stamp of the original directory X.

This change in time-date stamps can be awkward for a copy of a directory with a lot of downloaded Web pages: The HTML file of the Web page will have its original time-date stamp, but the corresponding subdirectory for files used by the HTML file will have the time-date stamp of the run of XCOPY. So, when sorting the copy on time date stamps, all the subdirectories, the HTML files and the corresponding subdirectories, e.g.,

Читайте также:  Исправление ошибок флешки linux

can appear far apart in the sort on time-date.

Hierarchical file systems go way back, IIRC to Multics at MIT in 1969, and since then lots of people have recognized the two cases, given a directory X, (i) copy directory X and all its contents and (ii) copy all the contents of X but not directory X itself. Well, if only from the experiments, XCOPY does only (ii).

So, the results of the 10 cases are below. For each case, in the results the first three lines have the first three arguments to XCOPY. So, the first line has the tree name of the directory to be copied, the ‘source’; the second line has the tree name of the directory to get the copies, the ‘destination’, and the third line has the options for XCOPY. The remaining 1-2 lines have the results of the run of XCOPY.

One big point about the options is that options /X and /O result in result

To see this, compare case 8 with the other cases that were the same, did not have /X and /O, but did copy.

These experiments have me better understand XCOPY and contribute an answer to the original question.

Batch file to copy files from one folder to another folder

I have a storage folder on a network in which all users will store their active data on a server. Now that server is going to be replaced by a new one due to place problem so I need to copy sub folders files from the old server storage folder to new server storage folder. I have below ex:

from \Oldeserver\storage\data & files to \New server\storage\data & files.

9 Answers 9

xcopy.exe is definitely your friend here. It’s built into Windows, so its cost is nothing.

Just xcopy /s c:\source d:\target

You’d probably want to tweak a few things; some of the options we also add include these:

  • /s/e — recursive copy, including copying empty directories.
  • /v — add this to verify the copy against the original. slower, but for the paranoid.
  • /h — copy system and hidden files.
  • /k — copy read-only attributes along with files. otherwise, all files become read-write.
  • /x — if you care about permissions, you might want /o or /x .
  • /y — don’t prompt before overwriting existing files.
  • /z — if you think the copy might fail and you want to restart it, use this. It places a marker on each file as it copies, so you can rerun the xcopy command to pick up from where it left off.

If you think the xcopy might fail partway through (like when you are copying over a flaky network connection), or that you have to stop it and want to continue it later, you can use xcopy /s/z c:\source d:\target .

Batch file to copy directories recursively [closed]

Want to improve this question? Update the question so it focuses on one problem only by editing this post.

Closed 14 days ago .

Is there a way to copy directories recursively inside a .bat file? Is an example of this available?

4 Answers 4

Look into xcopy, which will recursively copy files and subdirectories.

There are examples, 2/3 down the page. Of particular use is:

To copy all the files and subdirectories (including any empty subdirectories) from drive A to drive B, type:

After reading the accepted answer’s comments, I tried the robocopy command, which worked for me (using the standard command prompt from Windows 7 64 bits SP 1):

You may write a recursive algorithm in Batch that gives you exact control of what you do in every nested subdirectory:

Читайте также:  La network manager mac os

I wanted to replicate Unix/Linux’s cp -r as closely as possible. I came up with the following:

xcopy /e /k /h /i srcdir destdir

/e Copies directories and subdirectories, including empty ones.
/k Copies attributes. Normal Xcopy will reset read-only attributes.
/h Copies hidden and system files also.
/i If destination does not exist and copying more than one file, assume destination is a directory.

I made the following into a batch file ( cpr.bat ) so that I didn’t have to remember the flags:

Usage: cpr srcdir destdir

You might also want to use the following flags, but I didn’t:
/q Quiet. Do not display file names while copying.
/b Copies the Symbolic Link itself versus the target of the link. (requires UAC admin)
/o Copies directory and file ACLs. (requires UAC admin)

batch file to copy files to another location?

Is it possible to create a batch file to copy a folder to another location everytime I login, or when the folder is updated?

It could be written in VB or Java as well if not an easy solution.

8 Answers 8

When you login: you can to create a copy_my_files.bat file into your All Programs > Startup folder with this content (its a plain text document):

Use xcopy c:\folder\*.* d:\another_folder\. /Y to overwrite the file without any prompt.

Everytime a folder changes: if you can to use C#, you can to create a program using FileSystemWatcher

Type the following lines into it (obviously replace the folders with your ones)

Save the file as backup.bat (not .txt)

Double click on the file to run it. It will backup the folder and all its contents files/subfolders.

Now if you want the batch file to be run everytime you login in Windows, you should place it in Windows Startup menu. You find it under: Start > All Program > Startup To place the batch file in there either drag it into the Startup menu or RIGH click on the Windows START button and select Explore, go in Programs > Startup, and copy the batch file into there.

To run the batch file everytime the folder is updated you need an application, it can not be done with just a batch file.

Команда XCOPY — копирование файлов и каталогов.

Команда XCOPY используется для копирования файлов и каталогов с сохранением их структуры. По сравнению с командой COPY имеет более широкие возможности и является наиболее гибким средством копирования в командной строке Windows

Формат командной строки:

XCOPY источник [целевой_объект] [/A | /M] [/D[:дата]] [/P] [/S [/E]] [/V] [/W] [/C] [/I] [/Q] [/F] [/L] [/G] [/H] [/R] [/T] [/U] [/K] [/N] [/O] [/X] [/Y] [/-Y] [/Z] [/B] [/EXCLUDE:файл1[+файл2][+файл3]. ]

Параметры командной строки:

источник — Копируемые файлы.

целевой_объект — Расположение или имена новых файлов.

/A — Копирование только файлов с установленным архивным атрибутом; сам атрибут при этом не изменяется.

/M — Копирование только файлов с установленным архивным атрибутом; после копирования атрибут снимается.

/D:m-d-y — Копирование файлов, измененных не ранее указанной даты. Если дата не указана, заменяются только конечные файлы, более старые, чем исходные.

/EXCLUDE:файл1[+файл2][+файл3]. — Список файлов, содержащих строки с критериями для исключения файлов и папок из процесса копирования. Каждая строка должна располагаться в отдельной строке файла. Если какая-либо из строк совпадает с любой частью абсолютного пути к копируемому файлу, такой файл исключается из операции копирования. Например, указав строку \obj\ или .obj, можно исключить все файлы из папки obj или все файлы с расширением OBJ соответственно.

/P — Вывод запросов перед созданием каждого нового файла.

/S — Копирование только непустых каталогов с подкаталогами.

/E — Копирование каталогов с подкаталогами, включая пустые. Эквивалентен сочетанию ключей /S /E. Совместим с ключом /T.

/V — Проверка размера каждого нового файла.

/W — Вывод запроса на нажатие клавиши перед копированием.

/C — Продолжение копирования вне зависимости от наличия ошибок.

/I — Если целевой объект не существует и копируется несколько файлов, считается, что целевой объект задает каталог.

Читайте также:  Ошибка windows 0 000000f4

/Q — Запрет вывода имен копируемых файлов.

/F — Вывод полных имен исходных и целевых файлов.

/L — Вывод имен копируемых файлов.

/G — Копирование зашифрованных файлов в целевой каталог, не поддерживающий шифрование.

/H — Копирование, среди прочих, скрытых и системных файлов.

/R — Перезапись файлов, предназначенных только для чтения.

/T — Создание структуры каталогов без копирования файлов. Пустые каталоги и подкаталоги не включаются в процесс копирования. Для создания пустых каталогов и подкаталогов используйте сочетание ключей /T /E.

/U — Копирование только файлов, уже имеющихся в целевом каталоге.

/K — Копирование атрибутов. При использовании команды XСOPY обычно сбрасываются атрибуты «Только для чтения».

/N — Использование коротких имен при копировании.

/O — Копирование сведений о владельце и данных ACL.

/X — Копирование параметров аудита файлов (подразумевает ключ /O).

/Y — Подавление запроса подтверждения на перезапись существующего целевого файла.

/-Y — Запрос подтверждения на перезапись существующего целевого файла.

/Z — Копирование сетевых файлов с возобновлением.

/B — Копирование символической ссылки вместо ее целевого объекта.

/J — Копирование с использованием небуферизованного ввода/вывода. Рекомендуется для очень больших файлов.

Ключ /Y можно установить через переменную среды COPYCMD.

Ключ /-Y командной строки переопределяет такую установку.

Примеры использования XCOPY

XCOPY /? — выдать краткую справку по использованию команды.

xcopy C:\users D:\copy1 — скопировать файлы из каталога C:\users в каталог D:\copy1 . Будет выполняться копирование без подкаталогов и только файлов без атрибутов «Скрытый» и «Системный». Для скопированных файлов будет установлен атрибут Архивный . Если каталог, в который выполняется копирование, не существует, то пользователю будет выдано сообщение:

Что означает D:\copy1:
имя файла или каталога
(F = файл, D = каталог)? D

После ответа D целевой каталог будет создан и копирование будет выполняться в D:\COPY1\. Для подавления запроса на создание целевого каталога используется параметр /I:

xcopy C:\users D:\copy1 /I

xcopy C:\users D:\copy1 /H /Y /C — копирование файлов, включая скрытые и системные, с подавлением запроса на перезапись существующих и возобновлением при ошибке. Если существующий в целевом каталоге файл имеет атрибут «Только чтение», то копирование не выполняется. Для перезаписи таких файлов используется ключ /R

xcopy C:\users D:\copy1 /H /Y /C /R /S — скопировать все файлы и подкаталоги ( /S ) с перезаписью существующих без запроса ( /Y ) , включая скрытые и системные. ( /H ) с перезаписью файлов с атрибутом «Только чтение» (/R) и игнорированием ошибок ( /C )

xcopy C:\users D:\copy1 /H /Y /C /R /S /EXCLUDE:C:\users\listnotcopy.txt — то же, что и в предыдущем случае, но текстовый файл C:\users\listnotcopy.txt задает признаки исключения из процедуры копирования. Пример содержимого файла:

\User1\ — исключить из копирования каталог C:\users\user1
All Users исключить из копирования каталог C:\users\All Users
de*.* — исключить из копирования все файлы и каталоги, начинающиеся на буквосочетание «de»

xcopy C:\users\*.exe D:\copy1 /H /Y /C /R /S /EXCLUDE:C:\users\listnotcopy.txt — то же, что и в предыдущем примере, но выполняется только копирование исполняемых файлов с расширением .exe .

xcopy %TEMP%\*.ini D:\copy1\ini /H /Y /C /R /S /I — копирование всех файлов с расширением .ini из каталога временных файлов в каталог D:\copy1\ini\ . Если целевой подкаталог \ini\ не существует, то он будет создан без запроса пользователю ( /I ) .

xcopy %TEMP%\*.ini D:\copy1\ini /H /Y /C /R /S /I /D:09-16-2013 — то же, что и в предыдущем примере, но выполняется копирование только тех файлов, у которых установлена дата изменения 16 сентября 2013 года и старше.

xcopy C:\ D:\copy1\LISTDIR /H /Y /C /R /S /I /E /T — создать структуру папок диска C: в каталоге D:\copy1\LISTDIR . Копирование файлов не выполняется. Копируются только папки, включая пустые, скрытые и системные.

xcopy C:\ D:\copy1\LISTDIR /H /Y /C /R /S /I /E /T /D:09-16-2013 воссоздать в каталоге D:\copy1\LISTDIR структуру папок диска C: , с датой изменения 16 сентября 2013 года и позже.

Для добавления новых файлов в каталоги и обновления существующих на более поздние версии, можно использовать команду REPLACE.

Если вы желаете поделиться ссылкой на эту страницу в своей социальной сети, пользуйтесь кнопкой «Поделиться»

Оцените статью