Windows copy command syntax and examples
Using copy command, we can copy files from one directory to another directory. This command is similar to the Linux cp command, but it does not match with the full functionality of cp. Windows copy command can be used to copy files only, we can’t copy directories.
The syntax and usecases of copy command are explained below with examples.
Copy the contents of a file to another file
Example: To copy a file from c:\data\file1.doc to D:\backup\file2.doc
If the destination file already exists you will be prompted for confirmation. To suppress this confirmation you can use /Y switch with copy command. This would be useful if you are executing copy command from a batch file.
If the destination file exists, the above command will overwrite the same without asking the user for confirmation.
Copy file to another directory
When we specify a directory path as the destination, the files will be copied with the same name. We can assign a different name by specifying the new name in the destination path. Example is shown below.
To copy the file 1.doc loated at c:\data\documents to the directory c:\data\newdocs
Copy files with white space in name
If the file name has white space within it, we can wrap up the name in double quotes.
Example: To copy file, my resume.doc to another folder
Copy multiple files
We can’t specify multiple file names in copy command. However, we can use wildcards to identify a group of files and then copy all of them in a single command.
For example, to copy all excel files from current folder to another folder F:\backup
To copy all files in current folder to another folder
Use of environment variables
We can use environment variables in the copy command to specify the path of the folders. Like USERPROFILE, SystemRoot, ProgramFiles, TEMP, WINDIR, APPDATA, HOMEPATH.
For example, to copy a file to a user’s documents folder
The above command copies the file to the My Documents folder of the current logged in user.
You may also want to read
Windows «copy» is funny. Type «copy 1 2» and the file «1» will be copied into a new file «2». Now separate them by a plus sign instead of a space (copy 1+2) and you’ll concatenate 1 and 2 and replace the old file «1» with the result of the concatenation!
Yes, we can concatenate two or more files using copy command. You need to separate the list of files using +. You can redirect the resultant data to a new file also.
The above command will not alter the file 1. It creates a new file 3 with the concatenated data of 1 & 2. If no file name is provided it stores the result in the first file.
My Win7 cannot find a copy command, and when i run xcopy, a window flashes and exits.
I have the same problem. If you solved it, could you please explain how?
If you can not find your copy.exe file, you can download it to your windows directory or C:\ Directory depending the setting on your OS you should also be able to copy and run it from system32 or system folder.
how can i combine 2 .exe files and be able to use both after concatenation
I want to copy 2 different files(.exe,.config) from source to destination server of windows.
can you please help me on this command.
Hello i have a problem with my cmd windows 7.when i try to copy a command. Like help > file.pdf. i mean in extension pdf because i have this problem only with .pdf extension but not with .txt.So whe i execute the command. No problem. Then when i go to open the file.pdf ftom user destination the file.pdf doesn’t open say that is corrupted.please do help me .thanks
i have a file contain many lines as sources and another file has the same numbre of lines as destinations. i want to copy first line as source( c:/test/*.txt) to first line in destination ( d:/test2/), secend line ( c:/test/*.pdf) to second line in destination ( E:/test3/)……
Can I use the DOS/Windows “COPY” command in a BAT file to copy a file or a short string of text to computer memory and then paste (Ctrl +V) that string or file into a document?
xcopy xcopy
Копирует файлы и каталоги, включая подкаталоги. Copies files and directories, including subdirectories.
В разделе Примеры показан принцип использования этой команды. For examples of how to use this command, see Examples.
Синтаксис Syntax
Параметры Parameters
Параметр Parameter | Описание Description |
---|---|
Обязательный элемент. Required. Указывает расположение и имена файлов, которые необходимо скопировать. Specifies the location and names of the files you want to copy. Этот параметр должен содержать либо диск, либо путь. This parameter must include either a drive or a path. | |
[ ] [ ] | Указывает назначение файлов, которые необходимо скопировать. Specifies the destination of the files you want to copy. Этот параметр может включать букву диска и двоеточие, имя каталога, имя файла или их сочетание. This parameter can include a drive letter and colon, a directory name, a file name, or a combination of these. |
/W /w | Отображает следующее сообщение и ждет ответа перед началом копирования файлов: Displays the following message and waits for your response before starting to copy files: Нажмите любую клавишу, чтобы начать копирование файлов Press any key to begin copying file(s) |
/p /p | Запрос на подтверждение создания каждого целевого файла. Prompts you to confirm whether you want to create each destination file. |
/C /c | Игнорирует ошибки. Ignores errors. |
/v /v | Проверяет каждый файл по мере его занесения в целевой файл, чтобы убедиться, что файлы назначения идентичны исходным файлам. Verifies each file as it is written to the destination file to make sure that the destination files are identical to the source files. |
/q /q | Подавляет отображение сообщений xcopy . Suppresses the display of xcopy messages. |
/f /f | Отображает имена исходных и целевых файлов при копировании. Displays source and destination file names while copying. |
/l /l | Отображает список копируемых файлов. Displays a list of files that are to be copied. |
/g /g | Создает расшифрованные файлы назначения , если назначение не поддерживает шифрование. Creates decrypted Destination files when the destination does not support encryption. |
/d [: мм-дд-гггг] /d [:MM-DD-YYYY] | Копирует исходные файлы, измененные только в указанную дату или после нее. Copies source files changed on or after the specified date only. Если не включить значение mm-дд-гггг , команда xcopy скопирует все исходные файлы, которые новее существующих файлов назначения . If you do not include a MM-DD-YYYY value, xcopy copies all Source files that are newer than existing Destination files. Этот параметр командной строки позволяет обновлять измененные файлы. This command-line option allows you to update files that have changed. |
/U /u | Копирует файлы из источника , который существует только в месте назначения . Copies files from Source that exist on Destination only. |
/i /i | Если Source является каталогом или содержит подстановочные знаки, а назначение не существует, команда xcopy предполагает, что в поле назначение указано имя каталога и создается новый каталог. If Source is a directory or contains wildcards and Destination does not exist, xcopy assumes Destination specifies a directory name and creates a new directory. Затем команда xcopy копирует все указанные файлы в новый каталог. Then, xcopy copies all specified files into the new directory. По умолчанию команда xcopy предложит указать, является ли назначение файлом или каталогом. By default, xcopy prompts you to specify whether Destination is a file or a directory. |
/s /s | Копирует каталоги и подкаталоги, если они не пусты. Copies directories and subdirectories, unless they are empty. Если параметр /s опущен, то команда xcopy работает в одном каталоге. If you omit /s, xcopy works within a single directory. |
/e /e | Копирует все подкаталоги, даже если они пусты. Copies all subdirectories, even if they are empty. Используйте параметр /e с параметрами командной строки /s и /t . Use /e with the /s and /t command-line options. |
/t /t | Копирует структуру подкаталога (то есть только дерево), а не файлов. Copies the subdirectory structure (that is, the tree) only, not files. Чтобы скопировать пустые каталоги, необходимо включить параметр командной строки /e . To copy empty directories, you must include the /e command-line option. |
/k /k | Копирует файлы и оставляет атрибут только для чтения в целевых файлах, если они есть в исходных файлах. Copies files and retains the read-only attribute on Destination files if present on the Source files. По умолчанию xcopy удаляет атрибут «только для чтения». By default, xcopy removes the read-only attribute. |
/r /r | Копирует файлы, которые доступны только для чтения. Copies read-only files. |
/h /h | Копирует файлы с атрибутами скрытых и системных файлов. Copies files with hidden and system file attributes. По умолчанию команда xcopy не копирует скрытые или системные файлы. By default, xcopy does not copy hidden or system files |
/a /a | Копирует только исходные файлы, для которых заданы атрибуты файла архива. Copies only Source files that have their archive file attributes set. /a не изменяет атрибут файла архива исходного файла. /a does not modify the archive file attribute of the source file. Сведения о том, как задать атрибут файла архива с помощью attrib, см. в разделе Дополнительные ссылки. For information about how to set the archive file attribute by using attrib, see Additional References. |
/m /m | Копирует исходные файлы, для которых заданы атрибуты файла архива. Copies Source files that have their archive file attributes set. В отличие от /a, /m отключает атрибуты файлов архива в файлах, указанных в источнике. Unlike /a, /m turns off archive file attributes in the files that are specified in the source. Сведения о том, как задать атрибут файла архива с помощью attrib, см. в разделе Дополнительные ссылки. For information about how to set the archive file attribute by using attrib, see Additional References. |
/n /n | Создает копии, используя короткие имена файлов или каталогов NTFS. Creates copies by using the NTFS short file or directory names. /n требуется при копировании файлов или каталогов с тома NTFS в том FAT или при использовании соглашения об именовании файловой системы FAT (то есть 8,3 символов) в целевой файловой системе. /n is required when you copy files or directories from an NTFS volume to a FAT volume or when the FAT file system naming convention (that is, 8.3 characters) is required on the Destination file system. В качестве целевой файловой системы можно использовать файловую систему FAT или NTFS. The Destination file system can be FAT or NTFS. |
/o /o | Копирует владение файлом и сведения о списке управления доступом на уровне пользователей (DACL). Copies file ownership and discretionary access control list (DACL) information. |
/x /x | Копирует параметры аудита файлов и сведения о системном списке управления доступом (SACL) (подразумевается /o). Copies file audit settings and system access control list (SACL) information (implies /o). |
/exclude: имя_файла1 [+ [Имя_файла2] [+ [FileName3] ( ) ] /exclude:FileName1[+[FileName2][+[FileName3]( )] | Указывает список файлов. Specifies a list of files. Необходимо указать хотя бы один файл. At least one file must be specified. Каждый файл будет содержать строки поиска с каждой строкой в отдельной строке файла. Each file will contain search strings with each string on a separate line in the file. Если любая из строк соответствует любой части абсолютного пути к копируемому файлу, этот файл будет исключен из копирования. When any of the strings match any part of the absolute path of the file to be copied, that file will be excluded from being copied. Например, при указании строкового obj -файла будут исключены все файлы, расположенные в каталоге obj , или все файлы с расширением obj . For example, specifying the string obj will exclude all files underneath the directory obj or all files with the .obj extension. |
/y /y | Подавляет запрос на подтверждение перезаписи существующего целевого файла. Suppresses prompting to confirm that you want to overwrite an existing destination file. |
/-и /-y | Запрос на подтверждение перезаписи существующего целевого файла. Prompts to confirm that you want to overwrite an existing destination file. |
/z /z | Выполняет копирование по сети в перезапускаемом режиме. Copies over a network in restartable mode. |
/b /b | Копирует символьную ссылку вместо файлов. Copies the symbolic link instead of the files. Этот параметр появился в® Windows Vista. This parameter was introduced in Windows Vista®. |
/j /j | Копирует файлы без буферизации. Copies files without buffering. Рекомендуется для очень больших файлов. Recommended for very large files. Этот параметр был добавлен в Windows Server 2008 R2. This parameter was added in Windows Server 2008 R2. |
/? /? | Отображение справки в командной строке. Displays help at the command prompt. |
Комментарии Remarks
Использование /z Using /z
Если вы потеряли подключение на этапе копирования (например, если сервер переходит в режим «вне сети»), то после повторного подключения Подключение возобновится. If you lose your connection during the copy phase (for example, if the server going offline severs the connection), it resumes after you reestablish the connection. /z также отображает процент выполнения операции копирования для каждого файла. /z also displays the percentage of the copy operation completed for each file.
Использование /y в переменной среды копикмд. Using /y in the COPYCMD environment variable.
В переменной среды КОПИКМД можно использовать параметр /y . You can use /y in the COPYCMD environment variable. Эту команду можно переопределить с помощью /-и в командной строке. You can override this command by using /-y on the command line. По умолчанию выводится запрос на перезапись. By default, you are prompted to overwrite.
Копирование зашифрованных файлов Copying encrypted files
Копирование зашифрованных файлов на том, который не поддерживает EFS, приводит к ошибке. Copying encrypted files to a volume that does not support EFS results in an error. Сначала расшифровать файлы или скопировать их на том, который поддерживает EFS. Decrypt the files first or copy the files to a volume that does support EFS.
Добавление файлов Appending files
Чтобы добавить файлы, укажите один файл для назначения, но несколько файлов для источника (то есть с помощью подстановочных знаков или формата file1 + file2 + файл3). To append files, specify a single file for destination, but multiple files for source (that is, by using wildcards or file1+file2+file3 format).
Значение по умолчанию для назначения Default value for Destination
Если опустить назначение, команда xcopy скопирует файлы в текущий каталог. If you omit Destination, the xcopy command copies the files to the current directory.
Указание того, является ли назначение файлом или каталогом Specifying whether Destination is a file or directory
Если объект Destination не содержит существующий каталог и не заканчивается обратной косой чертой ( ) , появится следующее сообщение: If Destination does not contain an existing directory and does not end with a backslash (), the following message appears:
Нажмите клавишу F, если хотите скопировать файл или файлы в файл. Press F if you want the file or files to be copied to a file. Нажмите клавишу D, если хотите скопировать файл или файлы в каталог. Press D if you want the file or files to be copied to a directory.
Это сообщение можно отключить с помощью параметра командной строки /i , в результате чего команда xcopy предполагает, что назначение является каталогом, если источником является более одного файла или каталога. You can suppress this message by using the /i command-line option, which causes xcopy to assume that the destination is a directory if the source is more than one file or a directory.
Использование команды xcopy для установки атрибута архива для целевых файлов Using the xcopy command to set archive attribute for Destination files
Команда xcopy создает файлы с установленным атрибутом Archive, независимо от того, был ли этот атрибут задан в исходном файле. The xcopy command creates files with the archive attribute set, whether or not this attribute was set in the source file. Дополнительные сведения об атрибутах файлов и attrib см. в разделе Дополнительные ссылки. For more information about file attributes and attrib, see Additional References.
Сравнение xcopy и diskcopy Comparing xcopy and diskcopy
Если у вас есть диск, содержащий файлы в подкаталогах, и вы хотите скопировать его на диск, имеющий другой формат, используйте команду xcopy вместо команды diskcopy. If you have a disk that contains files in subdirectories and you want to copy it to a disk that has a different format, use the xcopy command instead of diskcopy. Так как команда diskcopy копирует диски по дорожке, исходный и целевой диски должны иметь одинаковый формат. Because the diskcopy command copies disks track by track, your source and destination disks must have the same format. Команда xcopy не имеет этого требования. The xcopy command does not have this requirement. Используйте xcopy , если вам не нужна полная копия образа диска. Use xcopy unless you need a complete disk image copy.
Коды выхода для команды xcopy Exit codes for xcopy
Для обработки кодов завершения, возвращаемых xcopy, используйте параметр ERRORLEVEL в командной строке If в пакетной программе. To process exit codes returned by xcopy, use the ErrorLevel parameter on the if command line in a batch program. Пример пакетной программы, обрабатывающей коды завершения с помощью If, см. в разделе Дополнительные ссылки. For an example of a batch program that processes exit codes using if, see Additional References. В следующей таблице перечислены все коды выхода и их описание. The following table lists each exit code and a description.
Код выхода Exit code | Описание Description |
---|---|
0 0 | Файлы были скопированы без ошибок. Files were copied without error. |
1 1 | Не найдены файлы для копирования. No files were found to copy. |
2 2 | Пользователь нажал клавиши CTRL + C для завершения команды xcopy. The user pressed CTRL+C to terminate xcopy. |
4 4 | Произошла ошибка инициализации. Initialization error occurred. Недостаточно памяти или места на диске, либо в командной строке введено недопустимое имя диска или недопустимый синтаксис. There is not enough memory or disk space, or you entered an invalid drive name or invalid syntax on the command line. |
5 5 | Произошла ошибка записи на диск. Disk write error occurred. |
Примеры Examples
1. чтобы скопировать все файлы и подкаталоги (включая все пустые подкаталоги) с диска A на диск B, введите: 1. To copy all the files and subdirectories (including any empty subdirectories) from drive A to drive B, type:
2. чтобы включить в предыдущий пример все системные или скрытые файлы, добавьте параметр командной строки /h следующим образом: 2. To include any system or hidden files in the previous example, add the/h command-line option as follows:
3. чтобы обновить файлы в каталоге \репортс с файлами в каталоге \равдата, которые были изменены с 29 декабря 1993 г., введите: 3. To update files in the \Reports directory with the files in the \Rawdata directory that have changed since December 29, 1993, type:
4. чтобы обновить все файлы, существующие в \репортс в предыдущем примере, независимо от даты, введите: 4. To update all the files that exist in \Reports in the previous example, regardless of date, type:
5. чтобы получить список файлов для копирования с помощью предыдущей команды (т. е. без фактического копирования файлов), введите: 5. To obtain a list of the files to be copied by the previous command (that is, without actually copying the files), type:
Файл xcopy. out содержит список всех копируемых файлов. The file xcopy.out lists every file that is to be copied.
6. чтобы скопировать каталог \кустомер и все подкаталоги в каталог \ \ публик\аддресс на сетевом диске H:, оставьте атрибут «только для чтения» и при создании нового файла в H: введите: 6. To copy the \Customer directory and all subdirectories to the directory \\Public\Address on network drive H:, retain the read-only attribute, and be prompted when a new file is created on H:, type:
7. чтобы выполнить предыдущую команду, убедитесь, что команда xcopy создает каталог \аддресс, если он не существует, и подавление сообщения, отображаемого при создании нового каталога, добавьте параметр командной строки /i следующим образом: 7. To issue the previous command, ensure that xcopy creates the \Address directory if it does not exist, and suppress the message that appears when you create a new directory, add the /i command-line option as follows:
8. можно создать пакетную программу для выполнения операций xcopy и использовать пакет If для обработки кода выхода при возникновении ошибки. 8. You can create a batch program to perform xcopy operations and use the batch if command to process the exit code if an error occurs. Например, в следующей пакетной программе для параметров источника и назначения xcopy используются заменяемые параметры: For example, the following batch program uses replaceable parameters for the xcopy source and destination parameters:
Чтобы использовать предыдущую пакетную программу для копирования всех файлов в каталоге К:\пргмкоде и его подкаталогов на диск B, введите: To use the preceding batch program to copy all files in the C:\Prgmcode directory and its subdirectories to drive B, type:
Интерпретатор команд подставляет к:\пргмкоде для %1 и B: для %2, затем использует xcopy с параметрами командной строки /e и /s . The command interpreter substitutes C:\Prgmcode for %1 and B: for %2, then uses xcopy with the /e and /s command-line options. Если при работе команды xcopy возникает ошибка, пакетная программа считывает код выхода и переходит к метке, указанной в соответствующей инструкции If ERRORLEVEL , а затем отображает соответствующее сообщение и завершает работу из пакетной программы. If xcopy encounters an error, the batch program reads the exit code and goes to the label indicated in the appropriate IF ERRORLEVEL statement, then displays the appropriate message and exits from the batch program.
9. в этом примере копируются все непустые каталоги, а также файлы, имя которых соответствует шаблону, заданному с помощью символа звездочки. 9. This example copies all the non-empty directories, plus files whose name match the pattern given with the asterisk symbol.