Скопировать папку в командной строке windows

Last Updated :
23 Sep, 2024

The xcopy command in Windows is a powerful tool for copying files and directories. It extends the functionality of the standard copy command by allowing the copy of entire directories along with their subdirectories and files all at once. This makes xcopy highly useful for tasks such as backing up files, migrating data, or automating file management tasks. In this article, we will cover what the xcopy command is how to use it, and provide some common use cases with examples.

Table of Content

  • What is the Xcopy Command?
  • How to Use the xcopy Command?
    • 1. Copy Files
    • 2. Copy Entire Directory
    • 3. Copy Directory Including Empty Folders
    • 4. Copy and Overwrite Files
    • 5. Copy Files Based on Date
    • 6. Copy Files in Quiet Mode
    • 7. Copy Files with Attributes
    • 8. Copy Files and Verify
    • 9. Copy Files Without Prompting for Destination Confirmation
  • Common xcopy Options
  • How to Use the Xcopy Command in Windows — FAQs

What is the Xcopy Command?

The xcopy (extended copy) command is used to copy files and directories including the subdirectories and files within them. Unlike the basic copy command, xcopy can handle large-scale directory copying making it perfect for backups, migrations, and file replication.

Basic Syntax:

xcopy [source] [destination] [options]

  • [source]: The path to the file or directory we want to copy.
  • [destination]: The path to where we want to copy the files.
  • [options]: The Various flags that control how the xcopy command behaves.

How to Use the xcopy Command?

1. Copy Files

To copy a file from one location to another using xcopy the basic syntax is:

xcopy C:\source\file.txt D:\destination\

This command copies file.txt from the C:\source directory to the D:\destination directory.

Example:

8

2. Copy Entire Directory

To copy an entire directory including all its subdirectories and files we can use the /s switch:

xcopy C:\source\ D:\destination\ /s

The /s option copies all directories and subdirectories except empty ones.

Example:

3. Copy Directory Including Empty Folders

If we also want to include the empty directories in the copy use the /e switch:

xcopy C:\source\ D:\destination\ /e

The /e switch copies all subdirectories including the empty ones.

Example:

4. Copy and Overwrite Files

If files in the destination already exist and we want to overwrite them we can use the /y option:

xcopy C:\source\ D:\destination\ /y

The /y option suppresses the prompt that asks if we want to overwrite the file.

Example:

5. Copy Files Based on Date

We can use the /d option to only copy files that have changed after a specific date or if they are newer than the destination files.

xcopy C:\source\ D:\destination\ /d

This ensures that only new or modified files are copied saving time and disk space.

Example:

6. Copy Files in Quiet Mode

To suppress output and avoid unnecessary prompts use the /q option:

xcopy C:\source\ D:\destination\ /q

This copies files quietly without listing each file.

Example:

7. Copy Files with Attributes

To copy system or hidden files we can use the /h option:

xcopy C:\source\ D:\destination\ /h

Normally, hidden and system files are not copied. The /h switch forces the xcopy command to the include them.

Example:

8. Copy Files and Verify

To ensure that files are copied correctly we can use the /v option which verifies each file after copying:

xcopy C:\source\ D:\destination\ /v

Example:

9. Copy Files Without Prompting for Destination Confirmation

Sometimes, xcopy will prompt to confirm whether the destination is a directory or a file. To avoid this we can add the /i option:

xcopy C:\source\ D:\destination\ /i

The /i option assumes the destination is a directory and automatically continues.

Example:

Common xcopy Options

Here are some commonly used xcopy options:

Option

Description

/s

The Copies directories and subdirectories except empty ones.

/e

The Copies of all subdirectories including the empty ones.

/y

Overwrites files without prompting for confirmation.

/d

Copies files that have changed since the last copy.

/v

The Verifies each file after copying to ensure accuracy.

/h

The Copies hid and system files.

/q

The Copies files in quiet mode suppressing output.

/i

Assumes the destination is a directory if it’s unclear.

/f

It displays the full source and destination of each file copied.

How-to-Use-the-Xcopy-Command-in-Windows

Xcopy Command in Windows

Conclusion

The xcopy command is a versatile and powerful tool in Windows allowing you to perform advanced file-copying tasks with ease. Whether we’re backing up directories copying only newer files or handling large sets of files across different drives, xcopy offers a range of options to suit your needs. By mastering this command we can save time streamline your file management tasks and ensure that data is efficiently copied with accuracy and precision.

При работе в командной строке (cmd) часто возникает необходимость скопировать файл или целую папку. Также консольные команды для копирования могут использоваться в BAT-файлах для резервного копирования и других задачах.

В этой статье мы расскажем о том, как скопировать файл или папку в командной строке Windows. Статья будет актуальной для всех версий Windows, включая самые новые Windows 11 и Windows 10.

Содержание

Как скопировать файл через командную строку Windows

Для копирования файлов в командной строке Windows нужно использовать команду «copy». Данная команда позволяет скопировать один или несколько файлов из одной папку в другую. Обратите внимание, команда «copy» копирует только файлы. Для копирования вложенных папок нужно использовать команду «xcopy», которую мы рассмотрим ниже.

В самом простом случае команда для копирования файлов выглядит так:

copy [исходный файл] [новый файл или папка назначения]

Например, чтобы скопировать файл «file1.txt» из текущего каталога в папку «e:\tmp» нужно выполнить:

copy file1.txt e:\tmp

скопировать файл в папку

При необходимости для копируемого файла можно указать новое название в папке назначения. Например, чтобы скопировать «file1.txt» из текущего каталога в папку «e:\tmp» и при этом назвать его «newfile.txt» нужно выполнить:

copy file1.txt e:\tmp\newfile.txt

указать новое название файла в папке назначения

С указанием полных путей команда копирования будет выглядеть так:

copy d:\tmp\file1.txt e:\tmp\file.txt

копирование с указанием полных путей

Для копирования большого количества файлов в названиях можно использовать маски. Символ звездочка (*) обозначает любое количество любых символов, а знак вопроса (?) – один любой символ. Например, чтобы скопировать все документы с расширением TXT из текущего каталога в папку «e:\tmp\» нужно выполнить следующее:

copy *.txt e:\tmp\

копирование с использованием маски

Также с помощью команды «copy» можно скопировать все содержимое одной папки в другую. Например, в случае копирования всех файлов из папки «d:\tmp\» в папку «e:\tmp» команда будет выглядеть так:

copy d:\tmp\ e:\tmp

скопировать все содержимое одной папки в другую

В данном случае из папки «d:\tmp\» будут скопированы только файлы. Для копирования вложенных папок нужно использовать «xcopy».

Полный синтаксис команды «copy» выглядит так:

copy [/d] [/v] [/n] [/y | /-y] [/z] [/a | /b] <source> [/a | /b] [+<source> [/a | /b] [+ ...]] [<destination> [/a | /b]]

Полный список параметров для команды «copy»:

Параметр Описание
/d Сохранение копируемых зашифрованные файлов в расшифрованном виде в месте назначения.
/v Проверка правильности записи скопированных файлов.
/n Использование короткого имени файла (если доступно) при копировании файла с именем длиннее восьми символов или с расширением длиннее трех символов.
/y Подавление запроса на подтверждение перезаписи.
/-y Вывод запроса на подтверждение перезаписи.
/z Копирует сетевые файлы в перезапускаемом режиме.
/a Копирование текстового файла ASCII.
/b Копирование двоичного файла.
<source> Указывает расположение, из которого необходимо скопировать один или несколько файлов. Обязательный параметр.
<destination> Указывает расположение, в которое необходимо скопировать файл или несколько файлов. Обязательный параметр.
/? Отображение справки в командной строке.

Большинство параметров указываются в начале, сразу после команды «copy». Например, для того чтобы подавить вывод запросов на перезапись существующих файлов можно добавить параметр «/y».

copy /y file1.txt file2.txt

Как скопировать папку через командную строку Windows

Для копирования папок с вложенными папками и файлами в командной строке Windows нужно использовать команду «xcopy». Данная команда позволяет скопировать папку из одного расположение в другое с сохранением структуры каталогов. Фактически «xcopy» — это более продвинутая версия команды «copy».

В упрощенном виде синтаксис команды «xcopy» будет выглядеть так:

xcopy [исходная папка или файл] [папка назначения или файл] [параметры]

Для копирования папок с вложенными папками и файлами нужно использовать параметр «/s» или «/e». Без этих параметров команда будет работать только с одним каталогом.

Параметр Описание
/s Копирование каталогов с подкаталогами (исключая пустые)
/e Копирование каталогов с подкаталогами (включая пустые).

Например, для того чтобы скопировать все файлы и вложенные папки (включая пустые) из папки «d:\tmp» в папку «e:\tmp» нужно выполнить:

xcopy d:\tmp e:\tmp /e

скопировать все файлы и вложенные папки

Полный синтаксис команды «xcopy» выглядит так:

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]

Полный список параметров для команды «xcopy» можно посмотреть на сайте Майкрософт. Здесь же приведены только некоторые самые базовые:

Параметр Описание
/s Копирование каталогов с подкаталогами (исключая пустые)
/e Копирование каталогов с подкаталогами (включая пустые).
/w Вывод запроса на подтверждения начала копирования.
/p Запрос подтверждение при создании каждого нового файла.
/c Пропуск ошибок.
/v Проверка всех скопированных файлов на соответствие его исходнику.
/q Скрывает вывод информации от команды xcopy.
/f Вывод имен в процессе копирования.
/l Вывод списка копируемых файлов.
/g Сохранение новых файлов в незашифрованном виде.
/d[:мм-дд-гггг] Копирование файлов, которые были измененные не ранее указанной даты. Если не указать дату (мм-дд-гггг), то команда xcopy будет копировать все файлы, которые новее существующих.
/u Обновление только существующих файлов в папке назначения.
/y Подавление запроса на подтверждение перезаписи.
/-y Вывод запроса на подтверждение перезаписи.
/z Копирует сетевые файлы в перезапускаемом режиме.
/h Копирование скрытых и системных файлов.
/r Перезапись файлов с атрибутом «только для чтения».
/t Создание структуры каталогов без копирования файлов. Пустые каталоги не включаются в структуру. Для включения пустых каталогов нужно добавить параметр /E.
<source> Указывает расположение, из которого необходимо скопировать один или несколько файлов. Обязательный параметр.
<destination> Указывает расположение, в которое необходимо скопировать файл или несколько файлов. Обязательный параметр.
/? Отображение справки в командной строке.

Параметры указываются в конце команды. Например, для того чтобы скопировать все файлы (включая скрытые, системные и только для чтения) и вложенные папки (включая пустые) из папки «d:\tmp» в папку «e:\tmp» нужно выполнить:

xcopy d:\tmp e:\tmp /e /h /r

Посмотрите также:

  • Выключение компьютера через командную строку
  • Как перезагрузить компьютер через командную строку
  • Как вызвать командную строку в Windows 7
  • Как поменять дату в Windows 7
  • Как выключить компьютер через определенное время

Автор
Александр Степушин

Создатель сайта comp-security.net, автор более 2000 статей о ремонте компьютеров, работе с программами, настройке операционных систем.

Остались вопросы?

Задайте вопрос в комментариях под статьей или на странице
«Задать вопрос»
и вы обязательно получите ответ.

Copy Files and Folders in Windows CMD with Copy and Xcopy

In this tutorial, we will learn how to copy files and folders in the Windows Command prompt.

We are going to look at two cmd commands: Copy and Xcopy.

Note that the copy command has some limitations compared to the xcopy. For example, to copy directories or hidden files, you have to use the xcopy command.

Copy Command

On Windows, we can use the copy command to copy one or more files from one location to another:

copy C:\data\sales.doc C:\backup

The preceding command will copy sales.doc from C:\data\ to C:\backup.

Use the /y switch to overwrite duplicate files without confirmation:

copy /y C:\data\sales.doc C:\backup

We can also save a file to a different name. For example, the following command saves file1.txt as file2.txt in the same directory:

copy file1.txt file2.txt

You can also use wildcards to copy multiple files:

copy /y C:\data\* C:\backup
copy /y C:\data\*.doc C:\backup

The first command copies all files in the C:\data\ directory to C:\backup. The second command copies all files with a .doc extension to the C:\backup.

windows copy command

We can also combine several files into one:

copy file1+file2 file3
copy error* C:\backup\report.txt

In the first line, file1 and file2 are combined to make one file named file3. In the second line, all files whose names start with «error» are copied to the C:\backup, as a single file called report.txt.

You can get a list of all available options with the copy /? command.

Xcopy Command

The xcopy command offers more features. For example, with xcopy, we can copy directories and subdirectories, as well as hidden files.

Command Options

/Y Prompt before overwriting an existing file.
/H Copy hidden files/system files.
/S Copy directories and subdirectories. Empty directories are not included by default (use /e for that).
/E Include empty directories.
/I Create the destination folder if it does not exist. Use this option when you want to copy the parent folder itself.
/T Copy directory tree without files. Empty directories are not included by default. Use /e option to include empty folders.
/P Prompt for confirmation before creating each file.
/Q Quiet mode.
/exclude Specify a text file that contains a list of files to exclude. See the examples.
/Z Resume mode. Use this option when copying files over a network.
/D:m-d-y Copies files changed on or after the specified date.

Examples of Using the Xcopy Command

Copy sales.doc from the current directory to C:\backup:

xcopy sales.doc C:\backup

Copy C:\data\accounts (all files including subdirectories) to C:\backup:

xcopy /s /e /h /i /y C:\data\accounts C:\backup\accounts
xcopy command

In the following example (without /I switch), the contents of the folder are copied but not the folder itself:

xcopy /s /e /h /y C:\data\accounts C:\backup\

Copy the directory structure of C:\OneDrive to the backup directory:

xcopy /s /e /t /y C:\OneDrive C:\backup\

You can use wildcard characters to match patterns. The following command copies all files with a .jpg extension:

xcopy /s /h /y C:\data\*.jpg C:\backup

Using for loop to copy multiple files:

for %i in (sales.doc, products.doc) do xcopy /y %i C:\backup

Excluding files with xcopy

With the /exclude, we can provide a text file that contains items we want to exclude.

xcopy /s /e /h /y /exclude:C:\Users\user1\files-to-exclude.txt C:\data\ C:\backup\

The files-to-exclude.txt may look like the following:

.doc
sales*

In this example, we exclude items with the .doc extension and files whose name starts with sales.

You can get a list of all available options with the xcopy /? command.

on November 25, 2010

Windows has two command line utilities to copy files/directories from command line. Copy command can be used to copy files from one folder to another folder. It can’t be used to copy a complete folder to another location on the disk. Xcopy allows us to do this. Let’s see how we can copy a directory along with all the files and sub directories to another location.

Xcopy /E /I SourceFolder DestinationFolder

Let’s say we need to copy a directory called C:\dir1\sourcedir to a location named D:\data\destinationdir.

Now you can run the below command to copy the complete sourcedir to D:\data\destination

Xcopy /E /I C:\dir1\sourcedir D:\data\destinationdir

In the above command we can also use relative paths of the folders with respect to the current directory.

Understanding the command

/E – This option makes sure that empty subfolders are copied to the destination.
/I – Avoids prompting if the destination is a folder or file. Not required if you are adding a trailing ‘\’ to the destination folder, like below.

Xcopy /E C:\dir1\sourcedir D:\data\destinationdir\

/S – This option is not required if you are using /E. /E ensures that all subfolders are also copied to the destination.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Безопасное извлечение устройства в windows 10 жесткий диск
  • Автономный установщик обновлений windows 10 ошибка 0x80004005
  • Kavremover для windows server 2003
  • Готовый web server windows
  • Какой телефон для активации windows