- Copy Folders and Subfolders using XCopy Command or Easier Way
- What is Xcopy command?
- Can I copy folders and subfolders using Xcopy command?
- Copy folders and subfolders using Xcopy command in Windows 7/8/10
- Situation 1. copy folders and subfolders and contents
- Situation 2. copy folders and subfolders without files
- Situation 3. copy folders and subfolders with NTFS and Share permission
- Easier way to copy files or folders in Windows 7/8/10
- Step by Step guide to copy folders files or folders via AOMEI Backupper
- Verdict
- copy copy
- Синтаксис Syntax
- Параметры Parameters
- Комментарии Remarks
- Примеры Examples
Copy Folders and Subfolders using XCopy Command or Easier Way
You will learn to use XCopy command to copy folders and subfolders for different requirements, not just files. Also, an easier way is prepared. Learn them first and then pick one per your needs.
By Nicky / Last Updated April 7, 2021
What is Xcopy command?
Xcopy is a command that can copy files, directories, and even entire drives from one location to another. It is an advanced version of the copy command that it has additional switches to specify both the source and the destination in detail. And it is useful in particular when copying files from CDROM to a hard drive because it will remove the read-only attribute automatically.
The Xcopy command is available in most current operating systems such as Windows 10, Windows 8, Windows 7, Windows XP, Windows Vista and Windows 98. The Xcopy command is also DOS command available in MS-DOS.
Can I copy folders and subfolders using Xcopy command?
“I have a folder with a lot of subfolders and files in them. Now, I want to copy the folder to another location, but I don’t want to recreate directory structures. Can I use Xcopy command to copy the directory structure of the folder and subfolders to another location?”
As we know, recreating directory structures can be a tedious and error-prone thing, especially if using the right-click method to create multiple structures and folders. So, you may want to copy folders and subfolders by Xcopy command directly. If you don’t know how to achieve it via Xcopy, keep reading to learn the detailed steps.
Copy folders and subfolders using Xcopy command in Windows 7/8/10
To move folders and subfolders in cmd, the most used command syntax would be:
xcopy [source] [destination] [options]
And there are plenty of options and switches for different demands. You can copy folders and subfolders including or excluding files from one location to another location by following the steps in different situations.
Situation 1. copy folders and subfolders and contents
1. Click Start and type cmd in the search box. Right-click Command Prompt from the list and select Run as administrator.
2. Now, when you’re in the command prompt, you can type Xcopy command as below to copy folders and subfolders including contents. For example, you want to copy “test” folder and its subfolders on C drive to D drive, type Xcopy command as:
Xcopy C:\test D:\test /E /H /C /I
/E – Copy subdirectories, including any empty ones.
/H — Copy files with hidden and system file attributes
/C — Continue copying even if an error occurs.
/I — If in doubt, always assume the destination is a folder. e.g. when the destination does not exist.
Xcopy will not copy open files.
Xcopy doesn’t display any progress or completed operations information when executed.
Remember that for folders with spaces in the name or folders larger than 8 characters in length, it is a good idea to put quotation marks around the path as in the figure above or you may get an error.
Situation 2. copy folders and subfolders without files
You can open the Command Prompt according to the steps shown above. Then, type the Xcopy command as below to copy folders and subfolders without files:
Xcopy Source Destination /T /E
/T — Copy the subdirectory structure, but not the files.
/E — Copy subdirectories, including any empty ones.
Situation 3. copy folders and subfolders with NTFS and Share permission
Sometimes, you may need to transfer the NTFS and Share permission together with your folders. Once the Command Prompt is open, you can then type the following command to copy all files and folders and retain its NTFS and Share permissions.
Xcopy Source Destination /O /X /E /H /K
/E — Copy folders and subfolders, including empty ones.
/H — Copy hidden and system files also.
/K — Copy attributes. Typically, Xcopy resets read-only attributes.
/O — Copy file ownership and ACL information.
/X — Copy file audit settings (implies /O).
Actually, there are many syntaxes for the Xcopy command, and you should use different syntaxes for different situations. Under most circumstances, you need to use several syntaxes at the same time. But if one syntax is used incorrectly, the Xcopy command may refuse to work, even worse, you may lose files. Therefore, you must be very careful when using the Xcopy command.
In fact, most users are not familiar with the use of the command line, and you may be confused with a large number of syntaxes. Therefore, you can copy folders and files in an easier way using a third-party migration tool like AOMEI Backupper Standard.
Easier way to copy files or folders in Windows 7/8/10
AOMEI Backupper Standard is a free and reliable backup software for Windows Vista/XP/7/8/10. It allows you to backup folders/files to different places like internal hard drive, external hard drive, USB drive, network and so on. This software has a clear interface and user-friendly design, so, you can figure it out quickly even for the first time.
In addition, this software has many useful features. For example, it supports scheduled backup, which can help you automatically backup folders/files in Daily, Weekly, Monthly, and Event-triggerВ mode. Furthermore, Full backup and Incremental backup are also supported. You can set incremental backup to save both your storage disk space and backup time.
Step by Step guide to copy folders files or folders via AOMEI Backupper
1.В Download AOMEI Backupper Standard, install and launch it.
2. Click Backup and File Backup subsequently.
3. Click Add File or Add Folder to choose the files or folders you want to backup and then click OK.
вњЋ Note: After clicking Add Folder, you can open Filter Settings to set file inclusion/exclusion mask. This function can help you backup files with specific file extension, you can upgrade to paid versions to enjoy it.
4. Select the destination path you want to copy files to. Internal hard drive, connected external hard drive, Cloud drive, shared folder, and NAS are available.
5. (Optional) Click Schedule to set a Daily/Weekly/Monthly under General tab, or select Full and Incremental backup under Advanced tab. Then, click Start Backup.
Verdict
You can copyВ foldersВ andВ subfolders using Xcopy command by the steps shown above. However, many users say that copying failed due to Xcopy not working sometimes, or Xcopy does not copy all files. And in some cases, Xcopy halts because of “Insufficient Memory” error or invalid number of parameters.В
Therefore, using AOMEI Backupper to copy folders or files is a more reliable and convenient method. With only a few clicks, you can copy folders or files to your destination, and its useful features like incremental backup, USB plug in, etc. bring you much convenience.
Moreover, AOMEI Backupper Standard designs for Windows XP/Vista/7/8/10 only, if you are a Windows Server user, you can try another version–AOMEI Backupper Server.
copy copy
Копирует один или несколько файлов из одного расположения в другое. Copies one or more files from one location to another.
В консоли восстановления можно также использовать команду Копировать с другими параметрами. You can also use the copy command, with different parameters, from the Recovery Console. Дополнительные сведения о консоли восстановления см. в разделе Среда восстановления Windows (Windows RE). For more information about the recovery console, see Windows Recovery Environment (Windows RE).
Синтаксис Syntax
Параметры Parameters
Параметр Parameter | Описание Description |
---|---|
/d /d | Позволяет сохранить копируемые зашифрованные файлы в виде расшифрованных файлов в месте назначения. Allows the encrypted files being copied to be saved as decrypted files at the destination. |
/v /v | Проверяет, правильно ли записаны новые файлы. Verifies that new files are written correctly. |
/n /n | Использует короткое имя файла (если доступно) при копировании файла с именем длиннее восьми символов или с расширением имени файла длиннее трех символов. Uses a short file name, if available, when copying a file with a name longer than eight characters, or with a file name extension longer than three characters. |
/y /y | Подавляет запрос на подтверждение перезаписи существующего целевого файла. Suppresses prompting to confirm that you want to overwrite an existing destination file. |
/-и /-y | Выводит запрос на подтверждение перезаписи существующего целевого файла. Prompts you to confirm that you want to overwrite an existing destination file. |
/z /z | Копирует сетевые файлы в перезапускаемый режим. Copies networked files in restartable mode. |
/a /a | Указывает текстовый файл ASCII. Indicates an ASCII text file. |
/b /b | Указывает на двоичный файл. Indicates a binary file. |
Обязательный элемент. Required. Указывает расположение, из которого необходимо скопировать файл или набор файлов. Specifies the location from which you want to copy a file or set of files. Источник может состоять из буквы диска и двоеточия, имени каталога, имени файла или их сочетания. Source can consist of a drive letter and colon, a directory name, a file name, or a combination of these. | |
Обязательный элемент. Required. Указывает расположение, в которое необходимо скопировать файл или набор файлов. Specifies the location to which you want to copy a file or set of files. Назначение может состоять из буквы диска и двоеточия, имени каталога, имени файла или их сочетания. Destination can consist of a drive letter and colon, a directory name, a file name, or a combination of these. | |
/? /? | Отображение справки в командной строке. Displays help at the command prompt. |
Комментарии Remarks
Можно скопировать текстовый файл ASCII, в котором используется символ конца файла (CTRL + Z), чтобы указать конец файла. You can copy an ASCII text file that uses an end-of-file character (CTRL+Z) to indicate the end of the file.
Если параметр /a предшествует или следует за списком файлов в командной строке, он применяется ко всем файлам, перечисленным до тех пор, пока не встретится копия . If /a precedes or follows a list of files on the command line, it applies to all files listed until copy encounters /b. В этом случае /b применяется к файлу, предшествующему /b. In this case, /b applies to the file preceding /b.
Действие /a зависит от его расположения в строке командной строки: The effect of /a depends on its position in the command-line string: — Если после Source указано значение /a , команда Copy обрабатывает файл как ASCII-файл и копирует данные, предшествующие первому символу конца файла (Ctrl + Z). If /a follows source, the copy command treats the file as an ASCII file and copies data that precedes the first end-of-file character (CTRL+Z). — Если параметр /a следует за назначением, команда Copy добавляет символ конца файла (Ctrl + Z) в качестве последнего символа файла. If /a follows destination, the copy command adds an end-of-file character (CTRL+Z) as the last character of the file.
Если /b указывает интерпретатору команд считывать число байтов, указанное размером файла в каталоге. If /b directs the command interpreter to read the number of bytes specified by the file size in the directory. /b — это значение по умолчанию для Copy, если только копирование не объединяет файлы. /b is the default value for copy, unless copy combines files.
Если /b предшествует или следует за списком файлов в командной строке, он применяется ко всем файлам в списке до тех пор , пока не встретится параметр /a. If /b precedes or follows a list of files on the command line, it applies to all listed files until copy encounters /a. В этом случае /a применяется к файлу, предшествующему /a. In this case, /a applies to the file preceding /a.
Действие /b зависит от его позиции в командной строке:-if /b следует за источником, команда Copy копирует весь файл, включая любой символ конца файла (Ctrl + Z). The effect of /b depends on its position in the command–line string: — If /b follows source, the copy command copies the entire file, including any end-of-file character (CTRL+Z). -If /b следует за назначением, команда Copy не добавляет символ конца файла (Ctrl + Z). — If /b follows destination, the copy command doesn’t add an end-of-file character (CTRL+Z).
Если операция записи не может быть проверена, появляется сообщение об ошибке. If a write operation cannot be verified, an error message appears. Хотя ошибки записи редко возникают с помощью команды Copy , можно использовать /v для проверки правильности записи важных данных. Although recording errors rarely occur with the copy command , you can use /v to verify that critical data has been correctly recorded. Параметр командной строки /v также замедляет команду Copy , так как необходимо проверить каждый сектор, записанный на диске. The /v command-line option also slows down the copy command, because each sector recorded on the disk must be checked.
Если в переменной среды копикмд предустановлен параметр /y , его можно переопределить с помощью /-и в командной строке. If /y is preset in the COPYCMD environment variable, you can override this setting by using /-y at the command line. По умолчанию при замене этого параметра выводится запрос, если команда Copy не выполняется в пакетном скрипте. By default, you are prompted when you replace this setting, unless the copy command is executed in a batch script.
Чтобы добавить файлы, укажите один файл для назначения, но несколько файлов для источника (используйте символы-шаблоны или формат файла file1 + file2 + файл3 ). To append files, specify a single file for destination, but multiple files for source (use wildcard characters or file1+file2+file3 format).
Если во время фазы копирования теряется соединение (например, если сервер переходит в автономный режим), можно использовать копию/z , чтобы возобновить подключение после восстановления подключения. If the connection is lost during the copy phase (for example, if the server going offline breaks the connection), you can use copy /z to resume after the connection is re-established. Параметр /z также отображает процент завершения операции копирования для каждого файла. The /z option also displays the percentage of the copy operation that is completed for each file.
Имя устройства можно заменить одним или несколькими экземплярами источника или назначения. You can substitute a device name for one or more occurrences of source or destination.
Если назначением является устройство (например, COM1 или LPT1), параметр /b копирует данные на устройство в двоичном режиме. If destination is a device (for example, Com1 or Lpt1), the /b option copies data to the device in binary mode. В двоичном режиме copy/b копирует все символы (включая такие специальные символы, как CTRL + C, CTRL + S, CTRL + Z и ввод) на устройство в виде данных. In binary mode, copy /b copies all characters (including special characters such as CTRL+C, CTRL+S, CTRL+Z, and ENTER) to the device, as data. Однако если параметр /b не указан, данные копируются на устройство в режиме ASCII. However, if you omit /b, the data is copied to the device in ASCII mode. В режиме ASCII специальные символы могут привести к объединению файлов во время процесса копирования. In ASCII mode, special characters might cause files to combine during the copying process.
Если целевой файл не указан, создается копия с тем же именем, датой изменения и временем изменения, что и в исходном файле. If you don’t specify a destination file, a copy is created with the same name, modified date, and modified time as the original file. Новая копия хранится в текущем каталоге на текущем диске. The new copy is stored in the current directory on the current drive. Если исходный файл находится на текущем диске и в текущем каталоге, и не указан другой диск или каталог для целевого файла, команда Copy остановится и отобразится следующее сообщение об ошибке: If the source file is on the current drive and in the current directory and you do not specify a different drive or directory for the destination file, the copy command stops and displays the following error message:
Если в источнике указано несколько файлов, команда Copy объединяет их в один файл, используя имя файла, указанное в поле назначение. If you specify more than one file in source, the copy command combines them all into a single file using the file name specified in destination. Команда Copy предполагает, что Объединенные файлы являются файлами ASCII, если не используется параметр /b . The copy command assumes the combined files are ASCII files unless you use the /b option.
Чтобы скопировать файлы длиной 0 байт или скопировать все файлы и подкаталоги каталога, используйте команду xcopy. To copy files that are 0 bytes long, or to copy all of a directory’s files and subdirectories, use the xcopy command.
Чтобы назначить текущее время и дату файлу без изменения файла, используйте следующий синтаксис: To assign the current time and date to a file without modifying the file, use the following syntax:
Где запятые указывают, что конечный параметр был намеренно оставлен. Where the commas indicate that the destination parameter has been intentionally left out.
Примеры Examples
Чтобы скопировать файл с именем memo.doc для letter.doc на текущем диске и убедиться, что символ конца файла (Ctrl + Z) находится в конце скопированного файла, введите: To copy a file called memo.doc to letter.doc in the current drive and ensure that an end-of-file character (CTRL+Z) is at the end of the copied file, type:
Чтобы скопировать файл с именем перебора. Typ из текущего диска и каталога в существующий каталог с именем птиц , расположенный на диске C, введите: To copy a file named robin.typ from the current drive and directory to an existing directory named Birds that is located on drive C, type:
Если каталог птиц не существует, файл Renamed . Typ копируется в файл с именем птиц , расположенный в корневом каталоге на диске C. If the Birds directory doesn’t exist, the file robin.typ is copied into a file named Birds that is located in the root directory on the disk in drive C.
Чтобы объединить Mar89. rpt, Apr89. rpt и May89. rpt, расположенные в текущем каталоге, и поместить их в файл с именем Report (также в текущем каталоге), введите: To combine Mar89.rpt, Apr89.rpt, and May89.rpt, which are located in the current directory, and place them in a file named Report (also in the current directory), type:
При объединении файлов команда копирования помечает конечный файл текущими датой и временем. If you combine files, the copy command marks the destination file with the current date and time. Если параметр Destination не указан, файлы объединяются и сохраняются под именем первого файла в списке. If you omit destination, the files are combined and stored under the name of the first file in the list.
Чтобы объединить все файлы в отчете, если файл с именем Report уже существует, введите: To combine all files in Report, when a file named Report already exists, type:
Чтобы объединить все файлы в текущем каталоге, имеющие расширение txt, в один файл с именем Combined.doc, введите: To combine all files in the current directory that have the .txt file name extension into a single file named Combined.doc, type:
Чтобы объединить несколько двоичных файлов в один файл, используйте подстановочные знаки, включите /b. To combine several binary files into one file by using wildcard characters, include /b. Это предотвращает расинтерпретацию CTRL + Z в качестве символа конца файла в Windows. This prevents Windows from treating CTRL+Z as an end-of-file character. Например, введите: For example, type:
При объединении двоичных файлов результирующий файл может оказаться непригодным для использования из-за внутреннего форматирования. If you combine binary files, the resulting file might be unusable due to internal formatting.