Примечание
Для доступа к этой странице требуется авторизация. Вы можете попробовать войти или изменить каталоги.
Для доступа к этой странице требуется авторизация. Вы можете попробовать изменить каталоги.
Копирует файлы и каталоги, включая вложенные каталоги.
For examples of how to use this command, see Examples.
Syntax
xcopy <Source> [<Destination>] [/w] [/p] [/c] [/v] [/q] [/f] [/l] [/g] [/d [:MM-DD-YYYY]] [/u] [/i] [/s [/e]] [/t] [/k] [/r] [/h] [{/a | /m}] [/n] [/o] [/x] [/exclude:FileName1[+[FileName2]][+[FileName3]]] [{/y | /-y}] [/z] [/b] [/j] [/compress]
Parameters
Parameter | Description |
---|---|
<Источник> | Required. Указывает расположение и имена файлов, которые требуется скопировать. Этот параметр должен включать диск или путь. |
[<Назначение>] | Указывает назначение файлов, которые требуется скопировать. Этот параметр может включать букву диска и двоеточие, имя каталога, имя файла или комбинацию из них. |
/w | Отображает следующее сообщение и ожидает ответа перед началом копирования файлов: Нажмите любой ключ, чтобы начать копирование файлов. |
/p | Запрашивает подтверждение того, нужно ли создать каждый целевой файл. |
/c | Ignores errors. |
/v | Проверяет каждый файл так же, как он записывается в целевой файл, чтобы убедиться, что целевые файлы идентичны исходным файлам. |
/q | Подавляет отображение xcopy сообщений. |
/f | Отображает имена исходных и целевых файлов во время копирования. |
/l | Создает список файлов, которые копируются, но не копируются. |
/g | Creates decrypted destination files when the destination doesn't support encryption. |
/d [:MM-DD-YYYY] | Копирует исходные файлы, измененные только по указанной дате или после нее. If you don't include a MM-DD-YYYY value, xcopy copies all source files that are newer than existing destination files. Этот параметр командной строки позволяет обновлять измененные файлы. |
/u | Copies files from source that exist on destination only. |
/i | If source is a directory or contains wildcards and destination doesn't exist, xcopy assumes destination specifies a directory name and creates a new directory.
xcopy Затем копирует все указанные файлы в новый каталог. By default, xcopy prompts you to specify whether destination is a file or a directory. |
/s | Копирует каталоги и вложенные каталоги, если они не пусты. If you omit /s, xcopy works within a single directory. |
/e | Копирует все вложенные каталоги, даже если они пусты. Use /e with the /s and /t command-line options. |
/t | Копирует структуру подкаталога (т. е. дерево) только, а не файлы. To copy empty directories, you must include the /e command-line option. |
/k | Copies files and retains the read-only attribute on destination files if present on the source files. По умолчанию xcopy удаляет атрибут только для чтения. |
/r | Копирует файлы только для чтения. |
/h | Копирует файлы со скрытыми и системными атрибутами файлов. По умолчанию xcopy не копирует скрытые или системные файлы |
/a | Copies only source files that have their archive file attributes set. /a doesn't modify the archive file attribute of the source file. For information about how to set the archive file attribute by using attrib, see Related links. |
/m | Copies source files that have their archive file attributes set. Unlike /a, /m turns off archive file attributes in the files that are specified in the source. For information about how to set the archive file attribute by using attrib, see Related links. |
/n | Создает копии с помощью коротких файлов NTFS или имен каталогов. /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. The destination file system can be FAT or NTFS. |
/o | Копирует сведения о владении файлами и списке управления доступом (DACL). |
/x | Copies file audit settings and system access control list (SACL) information (implies /o). |
/exclude:FileName1[+[FileName2]][+[FileName3]( )] | Указывает список файлов. Необходимо указать по крайней мере один файл. Каждый файл содержит строки поиска с каждой строкой в отдельной строке в файле. Если любая из строк соответствует любой части абсолютного пути к копируемым файлам, этот файл исключается из копирования. For example, specifying the string obj will exclude all files underneath the directory obj or all files with the .obj extension. |
/y | Подавляет запрос на подтверждение того, что вы хотите перезаписать существующий целевой файл. |
/-y | Запрашивает подтверждение того, что вы хотите перезаписать существующий целевой файл. |
/z | Копирует по сети в режиме перезапуска. |
/b | Копирует символьную ссылку вместо файлов. Этот параметр появился в Windows Vista®. |
/j | Копирует файлы без буферизации. Рекомендуется для очень больших файлов. Этот параметр был добавлен в Windows Server 2008 R2. |
/compress | Запрос сетевого сжатия во время передачи файлов, где это применимо. |
/[- ]sparse |
Включает или отключает сохранение разреженного состояния файлов во время процесса копирования. If both parameters are specified, /-sparse overrides /sparse. |
/noclone | Не пытается клонирование блоков в качестве оптимизации. |
/? | Отображает справку в командной строке. |
Remarks
Using /z
Если вы потеряете подключение во время этапа копирования (например, если сервер будет отключен, он возобновляется после повторного завершения подключения. /z also displays the percentage of the copy operation completed for each file.
Using /y in the COPYCMD environment variable.
You can use /y in the COPYCMD environment variable. You can override this command by using /-y on the command line. По умолчанию вам будет предложено перезаписать.
Копирование зашифрованных файлов
Копирование зашифрованных файлов в том, который не поддерживает EFS, приводит к ошибке. Расшифруйте файлы сначала или скопируйте их в том, поддерживающий EFS.
Appending files
Чтобы добавить файлы, укажите один файл для назначения, но несколько файлов для источника (то есть с помощью подстановочных знаков или формата file1+file2+file3).
Default value for destination
If you omit destination, the
xcopy
command copies the files to the current directory.Specifying whether destination is a file or directory
If destination doesn't contain an existing directory and doesn't end with a backslash (), the following message appears:
Does <Destination> specify a file name or directory name on the target(F = file, D = directory)?
Нажмите клавишу F, если нужно, чтобы файл или файлы были скопированы в файл. Нажмите клавишу D, если требуется, чтобы файл или файлы были скопированы в каталог.
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.Using the
xcopy
command to set archive attribute for destination filesКоманда
xcopy
создает файлы с набором атрибутов архива, независимо от того, был ли этот атрибут задан в исходном файле. For more information about file attributes and attrib, see Related links.Сравнение
xcopy
иdiskcopy
Если у вас есть диск, содержащий файлы в подкаталогах, и вы хотите скопировать его на диск с другим форматом, используйте
xcopy
команду вместоdiskcopy
этого.diskcopy
Так как команда копирует диски, отслеживаемые по треку, исходные и целевые диски должны иметь одинаковый формат. Этаxcopy
команда не имеет этого требования. Используйтеxcopy
, если вам не нужна полная копия образа диска.Ошибка нехватки памяти
Ошибка "недостаточно памяти" может возникать при выполнении
xcopy
копирования файла или папки, путь к имени файла которого превышает 255 символов.Коды выхода для
xcopy
To process exit codes returned by
xcopy
, use the ErrorLevel parameter on the if command line in a batch program. For an example of a batch program that processes exit codes using if, see Related links. В следующей таблице перечислены код выхода и описание.Exit code Description 0 Файлы были скопированы без ошибок. 1 Никакие файлы не были найдены для копирования. 2 Пользователь нажимал клавиши CTRL+C, чтобы завершить работу xcopy
.4 Произошла ошибка инициализации. Недостаточно памяти или места на диске, или в командной строке введено недопустимое имя диска или недопустимый синтаксис. 5 Произошла ошибка записи диска.
Examples
1. To copy all the files and subdirectories (including any empty subdirectories) from drive A to drive B, type:
xcopy a: b: /s /e
2. To include any system or hidden files in the previous example, add the /h command-line option as follows:
xcopy a: b: /s /e /h
3. To update files in the \Reports directory with the files in the \Rawdata directory that have changed since December 29, 1993, type:
xcopy \rawdata \reports /d:12-29-1993
4. To update all the files that exist in \Reports in the previous example, regardless of date, type:
xcopy \rawdata \reports /u
5. To obtain a list of the files to be copied by the previous command (that is, without actually copying the files), type:
xcopy \rawdata \reports /d:12-29-1993 /l > xcopy.out
Файл xcopy.out выводит список всех файлов, которые необходимо скопировать.
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:
xcopy \customer h:\public\address /s /e /k /p
7. To issue the previous command, ensure that xcopy
creates the \Address directory if it doesn't exist, and suppress the message that appears when you create a new directory, add the /i command-line option as follows:
xcopy \customer h:\public\address /s /e /k /p /i
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
параметров источника и назначения:
@echo off
rem COPYIT.BAT transfers all files in all subdirectories of
rem the source drive or directory (%1) to the destination
rem drive or directory (%2)
xcopy %1 %2 /s /e
if errorlevel 4 goto lowmemory
if errorlevel 2 goto abort
if errorlevel 0 goto exit
:lowmemory
echo Insufficient memory to copy files or
echo invalid drive or command-line syntax.
goto exit
:abort
echo You pressed CTRL+C to end the copy operation.
goto exit
:exit
Чтобы использовать предыдущую пакетную программу для копирования всех файлов в каталогЕ C:\Prgmcode и его подкаталогах на диск B, введите следующее:
copyit c:\prgmcode b:
The command interpreter substitutes C:\Prgmcode for %1 and B: for %2, then uses xcopy
with the /e and /s command-line options. 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. This example copies all the non-empty directories, plus files with the associated file extension after the asterisk symbol.
xcopy .\toc*.yml ..\..\Copy-To\ /S /Y
rem Output example.
rem .\d1\toc.yml
rem .\d1\d12\toc.yml
rem .\d2\toc.yml
rem 3 File(s) copied
In the preceding example, this particular source parameter value .\toc*.yml copies the same 3 files even if its two path characters .\ were removed. However, no files would be copied if the asterisk wildcard was removed from the source parameter, making it just .\toc.yml.