Основные команды (Windows cmd) Windows статьи | Frantsuzzz

Availability

Xcopy is an external command available for the following Microsoft operating systems as xcopy.exe.

Benefits

There are several benefits or advantages of using Xcopy that you will learn as you progress in this guide. But below are some of the benefits of using Xcopy.

Copy files using unbuffered i/o

Buffered I/O corresponds to how the operating system buffers disk reads and writes in the file system cache. While buffering speeds up subsequent reads and writes to the same file, it comes at a cost. As a result, unbuffered I/O (or a raw file copy) is the preferred method for copying a large file.

This copy method reduces the file system cache overhead and prevents the file system cache from being easily flushed with large amounts of file data.

To copy large files using unbuffered I/O, you can append the /J switch to the Xcopy command, as shown below.

Copying all files and folders recursively

Aside from copying files from one folder to another, Xcopy also lets you copy folders and files recursively. And there are two ways you can do a recursive copy—with and without empty folders.

To copy all files and directories while ignoring empty directories, append the /S option to the end of the Xcopy command, as shown below.

On the other hand, to include empty directories during the recursive copy, add the /E option instead to the command.

Copying encrypted files

Xcopy also supports copying encrypted files to destinations that do not support encryption. Using the /G switch, Xcopy copies encrypted source files and creates decrypted destination files.

This copy mode is helpful, especially when backing up encrypted files to network shares or non-Encrypting File System (EFS) volumes.

Copying files and folders over the network

Not only can Xcopy copy files between locations on the same or different disks, but it can also copy files over the network. Unfortunately, copying files over the network is not always reliable. Network connections may suffer from short interruptions and, in some cases, total loss of connection.

Luckily, you can run Xcopy in restartable mode. Meaning, even if the copy progress stops due to a network error, the copy can resume after re-establishing the network connection. To run Xcopy in restartable mode, you’ll need to add the /Z switch to the command.

For example, the command below performs a recursive file copy from the C:Workarea folder to a network location. The /Z parameter makes Xcopy run in restartable mode.

Using the /Z switch, Xcopy also displays the file copy progress in percentage.

Copying files based on the archive attribute

Typically, backup programs remove a file’s archive attribute after a backup operation. After modifying a file (i.e., edit and save), Windows automatically resets the files archive attribute.

If you create a script to backup files using Xcopy, you can use the archive attribute to determine whether to copy or backup the file.

To copy files with the archive attribute, you can take advantage of the /A and /M switches. Which one of these switches to use depends on whether you want to preserve the file’s archive attribute or not.

The following command performs a recursive copy of files with the archive attribute only. The destination files will retain the archive attribute after the copy due to the /A switch.

In contrast, to remove the source file’s archive attribute after copying to the destination, specify the /M switch instead.

Copying files to a new folder

With Xcopy, you can copy files and create the destination directory on the fly. To do so, you need to append the /I option to the Xcopy command.

For example, the command below copies the files from the C:WorkareaDemo folder to the D:Workarea folder. If the destination folder does not exist, Xcopy creates the destination folder using the /I option.

Copying files with verification

Like any other tasks, copying files may not always return 100% successful results. Some files may become corrupted during transfer even if there are no visible errors.

With Xcopy, you can use the /V switch to verify that the destination and source files are identical based on their size after copying. Identical source and destination files indicate that the copy was successful and that file is intact.

The command below copies all files from C:WorkareaXCopyDemo to C:WorkareaBackup and verifies each file using the /V switch. The /F switch displays the source and destination files’ full path.

Copying folder structures

In some situations, backup scripts or programs may require you to pre-provision the destination before copying the files from the source. When needed, you can use Xcopy to replicate the source folder structure without the content.

To do so, run the Xcopy command with /T switch. Using the /T switch will cause Xcopy to copy only the directory tree structure to the destination but ignores the empty directories.

You can also add the /E switch to the command to include empty directories, as shown in the example command below.

Excluding files and folders from the copy

A powerful feature of Xcopy is its ability to exclude files from the copy process. To use this feature, you can leverage the /EXCLUDE switch. This switch accepts the names of the file(s) that contain the exclusion lists.

First, you need to create or have a file containing the exclusion list. For example, you can have a text file called Exclude.txt that contains the following entries. As you can see, the exclusion file can have specific file names, file extensions, and folders as entries.

To run Xcopy with exclusions, run the command below and specify the full path of the exclusion file to the /EXCLUDE switch. This command uses the C:WorkareaXCopyDemoExclude.txt file.

The result? Xcopy runs to copy files but skips the xyz.txt, Exclude.txt, all files with .pdf and .png extensions, and all files under the exclude directory.

Exit codes

Xcopy returns an exit code for an operation, which you can use to determine if the operation was successful. Exit codes are useful, especially if your task or script takes actions based on the exit code it receives.

The command shell will save exits code in the %ErrorLevel% variable. Your code can then examine the value of this variable to determine the outcome of the Xcopy operation.

Below is a table that lists all the Xcopy exit codes.

Exit CodePurpose
0This exit code means that there were no errors.
1This exit code means that Xcopy did not find any files to copy.
2This exit code means that the Xcopy was terminated by pressing CTRL C.
4This exit code means that an initialization error happened either because of insufficient memory or disk space or because you’ve entered invalid syntax.
5This exit code means that there was a disk write error.

Filtering files to copy

Suppose there are multiple files in the source folder and subfolders you want to copy. Xcopy allows you to input wildcards as a way to filter which files to copy.

:/>  Как посмотреть arp таблицу в Windows | Настройка серверов windows и linux

For example, the command below copies only the files with the .cs extension recursively from the root of the C: drive to the root of the E: drive. This command will also ignore errors and overwrites existing files without prompting for confirmation.

I attempted to use the above xcopy command and was not able to copy all files within my favorites folder

After further examination, Computer Hope also encountered this issue. However, we could copy the majority of all favorites using the command below. Also, consider using robocopy.

xcopy c:windowsfavorites*.* /e /k /i /c

We are under the impression this issue is generated because of the way that Internet Explorer saves the URL (favorite) using long file names with extended characters.

Including hidden and system files

By default, Xcopy does not include hidden and system files in copy operations. But if you need to force Xcopy to include hidden and system files, add the /H switch to the command.

The command below copies all files recursively, including hidden and system files. This command also ignores errors, creates the destination folders, and overwrites existing files.

Invalid number of parameters

This error typically occurs when the command you’ve entered contains space characters in it. To avoid this error, when typing a source or destination path that contains space characters, you should surround the path with double-quotes.

For example, if the path is C:Documents and Settings, enter the path as “C:Documents and Settings”.

Listing files to copy

If you have a file server containing a huge amount of files that you want to copy, perhaps to a backup location, testing out your Xcopy command first would be ideal. One situation when you’d want to test Xcopy is when you’re combining multiple Xcopy options.

Using the /L switch with Xcopy, you can simulate what would have happened when you issued the command by listing which files it would copy. This way, you can confirm whether your command will copy all the files that you intended.

Performing a differential copy

When you need to backup files from one location to another, Xcopy has an option that lets you perform a differential backup. Instead of copying all files, a differential backup only copies the files where the modified date falls on or after a date that you specify to the /D:m-d-y switch.

For example, to copy only the files with the modified date on or after April 01, 2021, run the command below. Additionally, this command performs a recursive copy, ignores errors, and overwrites existing files at the destination.

If you do not specify a date with the /D option, Xcopy will copy only the source files that are newer than the destination files.

Prerequisites

To follow along with the examples in this guide, you’ll need the following.

  • A Windows (server or client) computer. Xcopy comes built-in to Windows, and you don’t need to download anything else. This guide will use Windows 10 Build 1909.
  • Xcopy works on the command prompt or PowerShell, and this article assumes that you already have one open.

Preserving the read-only file attribute

Another attribute that Xcopy can handle and preserve is the file’s read-only attribute. By default, when Xcopy copies a read-only file, it removes the file’s read-only attribute at the destination. To stop Xcopy from removing the read-only attribute, append the /K switch to the command.

For example, the command below copies a read-only file to another location, and the resulting destination file will still have a read-only attribute. This command will also overwrite the destination file if the file exists.

As a side-effect of preserving the file as read-only, Xcopy cannot overwrite the same file in future copy operations. But, you can force Xcopy to overwrite read-only files by adding the /R switch.

Retaining file owner and acl information

Imagine creating a backup of an entire profile folder. Each file may have different owners or unique permissions. Should you need to restore those files, you’d want the same owners and permissions intact.

Related:How To Manage NTFS Permissions With PowerShell

Scripting with xcopy

Apart from using Xcopy interactively, you can reap its benefits better if you use it to automate tasks with scripts. Below are a couple of examples that demonstrate how you can use Xcopy in scripts.

Understanding the xcopy command

Xcopy is a command-line utility, which has been available out of the box since Windows 98. You can find this tool under the %WINDIR%system32 folder with the executable name xcopy.exe.

Compared to the Windows copy command, Xcopy is much more efficient in copying files and directories. In addition, Xcopy has more options that make it more customizable and lets you control the file copy behavior.

Windows 10 and 11 syntax and switches

XCOPY source [destination] [/A | /M] [/D[:date]] [/P] [/S [/E]] [/V] [/W] [/C] [/I] [/Q] [/F] [/L] [/G] [/H] [/R] [/T] [/U] [/K] [/N] [/O] [/X] [/Y] [/-Y] [/Z] [/B] [/J] [/EXCLUDE:file1[ file2][ file3]...] [/COMPRESS]

The switch /Y may be preset in the COPYCMD environment variable. This switch may be overridden with /-Y on the command line.

Windows 2000, xp, vista, 7, and 8 syntax and switches

XCOPY source [destination] [/A | /M] [/D[:date]] [/P] [/S [/E]] [/V] [/W] [/C] [/I] [/Q] [/F] [/L] [/H] [/R] [/T] [/U] [/K] [/N] [/O] [/X] [/Y] [/-Y] [/Z] [/B] [/J] [/EXCLUDE:file1[ file2][ file3]...]

The switch /Y may be preset in the COPYCMD environment variable that can be overridden with /-Y on the command line.

Windows 98 and older syntax and switches

Copies files and directory trees.

XCOPY source [destination] [/A | /M] [/D[:date]] [/P] [/S [/E]] [/W] [/C] [/I] [/Q] [/F] [/L] [/H] [/R] [/T] [/U] [/K] [/N]

Working with xcopy: usage examples

Now that you’re familiar with the Xcopy syntax and options, it’s time to begin actually using it by combining one or more options together. You’ll explore many different scenarios in the following sections to use Xcopy to copy files and folders.

Xcopy batch script to move data

Xcopy has no built-in functionality to move files and folders from the source to the destination. But, as a workaround, you can create a script that would Xcopy the files first and then delete the files from the source.

:/>  Настройка Linux-файрвола с помощью iptables в CentOS / RHEL 7 | Windows для системных администраторов

The code below will copy the files to the destination. And if the copy process was successful, the script will delete the files at the source. Copy the code below and save it in a new file called movefiles.bat.

Next, to execute the movefiles.bat batch file, invoke its name in the command prompt or PowerShell followed by the source and destination paths, as you did in the previous example.

Xcopy syntax reference

Xcopy lets you perform various file and folder copy operations. But first, you’ll need to understand its syntax and options. There are a lot of options that would change how Xcopy operates. To help you make sense of these options, the tables that follow will cover them in detail.

The first path designation refers to the source file(s); the second path designation refers to the destination file(s).

Команда cd

Текущий каталог можно изменить с помощью команды

CD [диск:][путь]

Путь к требуемому каталогу указывается с учетом приведенных выше замечаний. Например, команда CD выполняет переход в корневой каталог текущего диска. Если запустить команду CD без параметров, то на экран будут выведены имена текущего диска и каталога.

Команда copy

Одной из наиболее часто повторяющихся задач при работе на компьютере является копирование и перемещение файлов из одного места в другое. Для копирования одного или нескольких файлов используется команда COPY.

Синтаксис этой команды:

COPY [/A|/B] источник [/A|/B]  [  источник [/A|/B] [  ...]]

  [результат [/A|/B]] [/V][/Y|/–Y]

Краткое описание параметров и ключей команды COPY приведено в таблице.

Таблица 1.1. Параметры и ключи команды COPY

Параметр

Описание

источник

Имя копируемого файла или файлов

/A

Файл является текстовым файлом ASCII, то есть конец файла обозначается символом с кодом ASCII 26 (<Ctrl> <Z>)

/B

Файл является двоичным. Этот ключ указывает на то, что интерпретатор команд должен при копировании считывать из источника число байт, заданное размером в каталоге копируемого файла

результат

Каталог для размещения результата копирования и/или имя создаваемого файла

/V

Проверка правильности копирования путем сравнения файлов после копирования

/Y

Отключение режима запроса подтверждения на замену файлов

/-Y

Включение режима запроса подтверждения на замену файлов

Приведем примеры использования команды COPY.

Копирование файла abc.txt из текущего каталога в каталог D:PROGRAM под тем же именем:

   COPY abc.txt D:PROGRAM

Копирование файла abc.txt из текущего каталога в каталог D:PROGRAM под новым именем def.txt:

   COPY abc.txt D:PROGRAMdef.txt

Копирование всех файлов с расширением txt с диска A: в каталог ‘Мои документы’ на диске C:

   COPY A:*.txt "C:Мои документы"

Если не задать в команде целевой файл, то команда COPY создаст копию файла-источника с тем же именем, датой и временем создания, что и исходный файл, и поместит новую копию в текущий каталог на текущем диске. Например, для того, чтобы скопировать все файлы из корневого каталога диска A: в текущий каталог, достаточно выполнить такую краткую команду:

   COPY A:*.*

В качестве источника или результата при копировании можно указывать имена не только файлов, но и устройств компьютера. Например, для того, чтобы распечатать файл abc.txt на принтере, можно воспользоваться командой копирования этого файла на устройство PRN: COPY abc.txt PRN

Другой интересный пример: создадим новый текстовый файл и запишем в него информацию, без использования текстового редактора. Для этого достаточно ввести команду COPY CON my.txt, которая будет копировать то, что вы набираете на клавиатуре, в файл my.txt (если этот файл существовал, то он перезапишется, иначе — создастся). Для завершения ввода необходимо ввести символ конца файла, то есть нажать клавиши <Ctrl> <Z>.

Команда COPY может также объединять (склеивать) нескольких файлов в один. Для этого необходимо указать единственный результирующий файл и несколько исходных. Это достигается путем использования групповых знаков (? и *) или формата файл1 файл2 файл3. Например, для объединения файлов 1.txt и 2.txt в файл 3.txt можно задать следующую команду:

   COPY 1.txt 2.txt 3.txt

Объединение всех файлов с расширением dat из текущего каталога в один файл all.dat может быть произведено так:

   COPY /B *.dat all.dat

Ключ /B здесь используется для предотвращения усечения соединяемых файлов, так как при комбинировании файлов команда COPY по умолчанию считает файлами текстовыми.

Если имя целевого файла совпадает с именем одного из копируемых файлов (кроме первого), то исходное содержимое целевого файла теряется. Если имя целевого файла опущено, то в его качестве используется первый файл из списка. Например, команда COPY 1.txt 2.txt добавит к содержимому файла 1.txt содержимое файла 2.txt.

COPY /B 1.txt  ,,

Здесь запятые указывают на пропуск параметра приемника, что и приводит к требуемому результату.

Команда COPY имеет и свои недостатки. Например, с ее помощью нельзя копировать скрытые и системные файлы, файлы нулевой длины, файлы из подкаталогов. Кроме того, если при копировании группы файлов COPY встретит файл, который в данный момент нельзя скопировать (например, он занят другим приложением), то процесс копирования полностью прервется, и остальные файлы не будут скопированы.

Команда del

Удалить один или несколько файлов можно с помощью команды

DEL [диск:][путь]имя_файла [ключи]

Для удаления сразу нескольких файлов используются групповые знаки ? и *. Ключ /S позволяет удалить указанные файлы из всех подкаталогов, ключ /F – принудительно удалить файлы, доступные только для чтения, ключ /A[[:]атрибуты] – отбирать файлы для удаления по атрибутам (аналогично ключу /A[[:]атрибуты] в команде DIR).

Команда dir

Еще одной очень полезной командой является DIR [диск:][путь][имя_файла] [ключи], которая используется для вывода информации о содержимом дисков и каталогов. Параметр [диск:][путь] задает диск и каталог, содержимое которого нужно вывести на экран. Параметр [имя_файла] задает файл или группу файлов, которые нужно включить в список. Например, команда

DIR C:*.bat

выведет на экран все файлы с расширением bat в корневом каталоге диска C:. Если задать эту команду без параметров, то выводится метка диска и его серийный номер, имена (в коротком и длинном вариантах) файлов и подкаталогов, находящихся в текущем каталоге, а также дата и время их последней модификации.

Том в устройстве C имеет метку PHYS1_PART2
 Серийный номер тома: 366D-6107
 Содержимое папки C:aditor
.              <ПАПКА>      25.01.00  17:15 .
..             <ПАПКА>      25.01.00  17:15 ..
TEMPLT02 DAT           227  07.08.98   1:00 templt02.dat
UNINST1  000         1 093  02.03.99   8:36 UNINST1.000
HILITE   DAT         1 082  18.09.98  18:55 hilite.dat
TEMPLT01 DAT            48  07.08.98   1:00 templt01.dat
UNINST0  000        40 960  15.04.98   2:08 UNINST0.000
TTABLE   DAT           357  07.08.98   1:00 ttable.dat
ADITOR   EXE       461 312  01.12.99  23:13 aditor.exe
README   TXT         3 974  25.01.00  17:26 readme.txt
ADITOR   HLP        24 594  08.10.98  23:12 aditor.hlp
ТЕКСТО~1 TXT             0  11.03.01   9:02 Текстовый файл.txt
        11 файлов        533 647 байт
         2 папок     143 261 696 байт свободно

С помощью ключей команды DIR можно задать различные режимы расположения, фильтрации и сортировки. Например, при использовании ключа /W перечень файлов выводится в широком формате с максимально возможным числом имен файлов или каталогов на каждой строке. Например:

Том в устройстве C имеет метку PHYS1_PART2
 Серийный номер тома: 366D-6107
 Содержимое папки C:aditor
[.]                    [..]                   TEMPLT02.DAT       UNINST1.000           HILITE.DAT 
TEMPLT01.DAT       UNINST0.000           TTABLE.DAT           ADITOR.EXE           README.TXT 
ADITOR.HLP           ТЕКСТО~1.TXT
        11 файлов        533 647 байт
         2 папок     143 257 600 байт свободно

С помощью ключа /A[[:]атрибуты] можно вывести имена только тех каталогов и файлов, которые имеют заданные атрибуты (R — “Только чтение”, A — “Архивный”, S — “Системный”, H — “Скрытый”, префикс “–” имеет значение НЕ). Если ключ /A используется более чем с одним значением атрибута, будут выведены имена только тех файлов, у которых все атрибуты совпадают с заданными.

DIR C: /A:HS

а для вывода всех файлов, кроме скрытых — команду

DIR C: /A:-H

Отметим здесь, что атрибуту каталога соответствует буква D, то есть для того, чтобы, например, вывести список всех каталогов диска C:, нужно задать команду

DIR C: /A:D

Ключ /O[[:]сортировка] задает порядок сортировки содержимого каталога при выводе его командой DIR. Если этот ключ опущен, DIR печатает имена файлов и каталогов в том порядке, в котором они содержатся в каталоге. Если ключ /O задан, а параметр сортировка не указан, то DIR выводит имена в алфавитном порядке.

:/>  windows - batch file to check 64bit or 32bit OS - Stack Overflow

В параметре сортировка можно использовать следующие значения: N — по имени (алфавитная), S — по размеру (начиная с меньших), E — по расширению (алфавитная), D — по дате (начиная с более старых), A — по дате загрузки (начиная с более старых), G — начать список с каталогов.

Ключ /S означает вывод списка файлов из заданного каталога и его подкаталогов.

Ключ /B перечисляет только названия каталогов и имена файлов (в длинном формате) по одному на строку, включая расширение. При этом выводится только основная информация, без итоговой. Например:

templt02.dat
UNINST1.000
hilite.dat
templt01.dat
UNINST0.000
ttable.dat
aditor.exe
readme.txt
aditor.hlp
Текстовый файл.txt

Команда move

Синтаксис команды для перемещения одного или более файлов имеет вид:

MOVE [/Y|/–Y] [диск:][путь]имя_файла1[,...] результирующий_файл

Синтаксис команды для переименования папки имеет вид:

MOVE [/Y|/–Y] [диск:][путь]каталог1 каталог2

Здесь параметр результирующий_файл задает новое размещение файла и может включать имя диска, двоеточие, имя каталога, либо их сочетание. Если перемещается только один файл, допускается указать его новое имя. Это позволяет сразу переместить и переименовать файл. Например,

MOVE "C:Мои документысписок.txt" D:list.txt

Если указан ключ /-Y, то при создании каталогов и замене файлов будет выдаваться запрос на подтверждение. Ключ /Y отменяет выдачу такого запроса.

CD | COPY | XCOPY | DIR | MKDIR | RMDIR | DEL | REN | MOVE

Команда ren

Переименовать файлы и каталоги можно с помощью команды RENAME (REN). Синтаксис этой команды имеет следующий вид:

REN [диск:][путь][каталог1|файл1] [каталог2|файл2]

Здесь параметр каталог1|файл1 определяет название каталога/файла, которое нужно изменить, а каталог2|файл2 задает новое название каталога/файла. В любом параметре команды REN можно использовать групповые символы ? и *. При этом представленные шаблонами символы в параметре файл2 будут идентичны соответствующим символам в параметре файл1.

REN *.txt *.doc

Если файл с именем файл2 уже существует, то команда REN прекратит выполнение, и произойдет вывод сообщения, что файл уже существует или занят. Кроме того, в команде REN нельзя указать другой диск или каталог для создания результирующих каталога и файла. Для этой цели нужно использовать команду MOVE, предназначенную для переименования и перемещения файлов и каталогов.

Команда xcopy

Указанные при описании команды COPY проблемы можно решить с помощью команды XCOPY, которая предоставляет намного больше возможностей при копировании. Необходимо отметить, правда, что XCOPY может работать только с файлами и каталогами, но не с устройствами.

Синтаксис этой команды:

XCOPY источник [результат] [ключи]

Команда XCOPY имеет множество ключей, мы коснемся лишь некоторых из них. Ключ /D[:[дата]] позволяет копировать только файлы, измененные не ранее указанной даты. Если параметр дата не указан, то копирование будет производиться только если источник новее результата. Например, команда

   XCOPY "C:Мои документы*.*" "D:BACKUPМои документы" /D

скопирует в каталог ‘D:BACKUPМои документы’ только те файлы из каталога ‘C:Мои документы’, которые были изменены со времени последнего подобного копирования или которых вообще не было в ‘D:BACKUPМои документы’.

Ключ /S позволяет копировать все непустые подкаталоги в каталоге-источнике. С помощью же ключа /E можно копировать вообще все подкаталоги, включая и пустые.

Если указан ключ /C, то копирование будет продолжаться даже в случае возникновения ошибок. Это бывает очень полезным при операциях копирования, производимых над группами файлов, например, при резервном копировании данных.

Ключ /I важен для случая, когда копируются несколько файлов, а файл назначения отсутствует. При задании этого ключа команда XCOPY считает, что файл назначения должен быть каталогом. Например, если задать ключ /I в команде копирования всех файлов с расширением txt из текущего каталога в несуществующий еще подкаталог TEXT,

   XCOPY  *.txt TEXT /I

то подкаталог TEXT будет создан без дополнительных запросов.

Ключи /Q, /F и /L отвечают за режим отображения при копировании. При задании ключа /Q имена файлов при копировании не отображаются, ключа /F — отображаются полные пути источника и результата. Ключ /L обозначает, что отображаются только файлы, которые должны быть скопированы (при этом само копирование не производится).

С помощью ключа /H можно копировать скрытые и системные файлы, а с помощью ключа /R — заменять файлы с атрибутом “Только для чтения”. Например, для копирования всех файлов из корневого каталога диска C: (включая системные и скрытые) в каталог SYS на диске D:, нужно ввести следующую команду:

   XCOPY C:*.* D:SYS /H

Ключ /T позволяет применять XCOPY для копирования только структуры каталогов источника, без дублирования находящихся в этих каталогах файлов, причем пустые каталоги и подкаталоги не включаются. Для того, чтобы все же включить пустые каталоги и подкаталоги, нужно использовать комбинацию ключей /T /E.

Используя XCOPY можно при копировании обновлять только уже существующие файлы (новые файлы при этом не записываются). Для этого применяется ключ /U. Например, если в каталоге C:2 находились файлы a.txt и b.txt, а в каталоге C:1 — файлы a.txt, b.txt, c.txt и d.txt, то после выполнения команды

   XCOPY C:1 C:2 /U

в каталоге C:2 по-прежнему останутся лишь два файла a.txt и b.txt, содержимое которых будет заменено содержимым соответствующих файлов из каталога C:1.Если с помощью XCOPY копировался файл с атрибутом “Только для чтения”, то по умолчанию у файла-копии этот атрибут снимется. Для того, чтобы копировать не только данные, но и полностью атрибуты файла, необходимо использовать ключ /K.

Ключи /Y и /-Y определяют, нужно ли запрашивать подтверждение перед заменой файлов при копировании. /Y означает, что такой запрос нужен, /-Y — не нужен.

Команды mkdir и rmdir

Для создания нового каталога и удаления уже существующего пустого каталога используются команды MKDIR [диск:]путь и RMDIR [диск:]путь [ключи] соответственно (или их короткие аналоги MD и RD). Например:

MKDIR "C:Примеры"
RMDIR "C:Примеры"

Команда MKDIR не может быть выполнена, если каталог или файл с заданным именем уже существует. Команда RMDIR не будет выполнена, если удаляемый каталог не пустой.

Примеры команды xcopy

Чтобы копировать все файлы и подкаталоги (включая пустые подкаталоги) с диска A на диск B, введите:

xcopy a: b: /s /e.

Conclusion

If your job involves copying files in bulk or creating file backups, Xcopy is an excellent tool to help make your job easier. Xcopy delivers accurate and fast file copy results with many options to customize its behavior to fit your requirements.

Оставьте комментарий