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
copy sourceFile destinationFile
Example: To copy a file from c:\data\file1.doc to D:\backup\file2.doc
copy c:\data\file1.doc 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.
c\> copy /Y c:\dir1\subdir1\file1.txt c:\dir2\subdir2\file2.txt
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
c\> copy c:\data\documents\1.doc 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 "my resume.doc" D:\data\
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
copy *.xls F:\backup\
To copy all files in current folder to another folder
copy * D:\dir1\dir2
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
Copy D:\file.pdf %HOMEPATH%\Documents\
The above command copies the file to the My Documents
folder of the current logged in user.
You may also want to read
- Xcopy command syntax and examples
- Robocopy command
Last Updated :
05 Apr, 2025
Have you ever needed to copy a bunch of files from one folder to another without clicking through endless windows? Or perhaps you’re looking to streamline a repetitive task with a single line of text? If so, the Command Prompt (CMD) on Windows is here to save the day! Copying files between directories is a fundamental computing task, and while graphical interfaces are convenient, CMD offers a fast, efficient alternative—especially for bulk operations or automation. In this guide, we’ll show you how to use CMD to copy files from one directory to another.
Reason to Use CMD for Copying Files from One Directory to Another
When copying files from one directory to another, using the Command Prompt (CMD) offers several advantages over relying on a graphical user interface (GUI). Below are the key reasons why CMD can be a better choice for this task:
- Speed and Efficiency: CMD allows you to copy files quickly with a single command, avoiding the slower process of navigating folders and dragging files in a graphical interface.
- Automation and Scripting: CMD supports batch scripts, enabling you to automate or schedule repetitive file copying tasks or schedule them, which isn’t possible with manual GUI methods.
- Handling Large or Numerous Files: CMD is designed to efficiently handle large sets of files or big datasets, even resuming transfers if interrupted, unlike the GUI, which may struggle.
How to Copy Files from One Directory to Another Using CMD
In this section, we will outline the step-by-step procedure for copying files between directories using the Windows Command Prompt. This guide is divided into two parts: the first part covers copying a single file, while the second part discusses copying multiple files. Let’s begin with the first part.
How to Copy Files From One Directory to Another?
Follow the below steps to copy the single file from one directory to another.
Step 1: Open CMD
- To copy a file from one directory to another using CMD, open Command Prompt by pressing Win + R, typing CMD, and pressing Enter.
Step 1: Opne File Destination
- Go to the file destination though Change Directory«cd» command or open cmd in that directory.
Step 2: Use Dir Command
- Now Type «dir» command to see the list of files available in that directory.
Step 3: Use Copy Command
- Now type the following command and replace <filename> with your actual file name and <destination> with where you want to paste the file.
copy <filename> <destination>
Note: If you try to copy file to C: drive, so it does not work if you have not open command prompt «Run as Administrator» permission.
How to Copy Multiple Files from One Directory to Another?
To copy multiple files at once, use the appropriate command along with its various options. Follow the steps below to transfer all files and directories to a different directory or drive.
Step 1: Open CMD
- Press WIndows button and search for CMD now, choose run with Administrator option to open CMD.
Step 2: Use XCOPY Command
- Run the following command to copy from one directory to another. Replace <source> and <destination> with current directory location from where you want to copy and location where you want to paste.
xcopy <source> <destination> /s /e
Available Options
When copying files using the Command Prompt (CMD) in Windows, you can use a variety of options to make the process work just the way you want. Find a table of all available options that you can use ti copy files from one directory to another.
Parameters |
Description |
---|---|
<source> |
Give you the file name and location of the file you want to copy. |
<destination> |
Give you the directory name and location of the destination where you want to paste the file. |
/w |
Display the message and wait for your response. Press any key to begin copying file(s) |
/p |
It will ask you where you want to create a destination file. |
/c |
It specifies to ignore the error if occurs. |
/v |
It will verify each file is same as the source and destination file. |
/f |
displays the source and destination of the each file. |
/g |
Generate a list of files to be coppied. |
/s |
copies the directory and sub-directory unless it is empty. |
/e |
Copies all subdirectories does not check whether they are empty or not. |
/r |
It will copy only read-only files. |
/h |
copies hidden files. |
/z |
Copies over a network in restartable mode. |
/? |
Display the help. |
Conclusion
One effective and powerful technique to manage your files on Windows is to use the CMD copy command to move files between folders. The copy files using CMD approach is simple and dependable, regardless of the number of files you’re copying. You may now more efficiently manage your data because you know how to use CMD to copy files from one location to another.
Загрузить PDF
Загрузить PDF
Из этой статьи вы узнаете, как в Windows копировать отдельные файлы и файлы из папки с помощью командной строки.
-
Необходимо выяснить, в каком каталоге хранится файл, чтобы указать его в командной строке.
- Чтобы найти каталог, в Проводнике перейдите в папку с файлом, а затем щелкните по адресной строке в верхней части окна Проводника.
- Большинство файлов находится в следующем каталоге: [буква диска]:\Пользователи\[имя пользователя] (например, «C:\Пользователи\Иван»). В этом каталоге хранятся практически все файлы, созданные пользователем.
- Например, файл на рабочем столе находится в следующем каталоге: «C:\Пользователи\Иван\Рабочий стол», а файл в папке «Документы» в каталоге «C:\Пользователи\Иван\Документы».
-
Это необходимо, чтобы скопировать файл. Имейте в виду, что командная строка учитывает регистр букв, поэтому правильно запишите имя файла.
-
Нажмите на логотип Windows в нижнем левом углу экрана.
-
Начнется поиск утилиты «Командная строка».
-
Вы найдете этот значок в верхней части меню «Пуск». Откроется окно командной строки.
- Имейте в виду, что на общедоступном компьютере (например, в школе) вы не сможете открыть командную строку.
Реклама
-
Введите cd, а затем нажмите Пробел; клавишу ↵ Enter не нажимайте.
-
-
В командной строке вы перейдете в указанный каталог.
-
Введите copy, а затем нажмите Пробел; клавишу ↵ Enter не нажимайте.
-
Введите имя файла, а затем нажмите Пробел. Имя файла введите с расширением файла (например, .txt в случае текстового файла). Клавишу ↵ Enter не нажимайте.
- Если в имени файла есть пробелы, заключите их в кавычки. Например, имя файла «Pickles are Good.txt» в командной строке нужно ввести так: Pickles" "are" "Good.txt.
-
Введите каталог (например, C:\Пользователи\[ваше имя пользователя]\Рабочий стол, в который будет скопирован файл.
- Если не ввести конечный каталог, файл будет скопирован в ваш персональный каталог (например, «C:\Пользователи\[ваше имя пользователя]»).
-
Файл будет скопирован в указанный каталог. Чтобы открыть скопированный файл, перейдите в соответствующий каталог в окне Проводника.
Реклама
-
Введите cd, нажмите Пробел, введите каталог с папкой и нажмите ↵ Enter.
- Например, чтобы скопировать файлы из папки «Example», которая находится на рабочем столе, введите каталог C:\Пользователи\Иван\Рабочий стол.
-
Введите robocopy, а затем нажмите Пробел; клавишу ↵ Enter не нажимайте.
-
Введите имя папки, файлы из которой вы хотите скопировать, а затем нажмите Пробел. Клавишу ↵ Enter не нажимайте.
- Если в имени папки есть пробелы, заключите их в кавычки.
-
Введите каталог, в который вы хотите скопировать файлы из папки.
- Если в исходной и конечной папках много файлов, они перемешаются, потому что сама исходная папка скопирована не будет.
-
Файл из исходной папки будут скопированы в конечную папку.
Реклама
Советы
- Чтобы скопировать все файлы, которые находятся в каталоге, введите команду copy *[тип файла] (например, copy *.txt).
- Чтобы создать конечную папку и скопировать в нее сразу несколько файлов, введите каталог конечной папки (включая саму конечную папку) в сочетании с командой «robocopy».[1]
- Если скопировать файлы, которые находятся на рабочем столе, в новую папку, она будет переименована в «Рабочий стол».
Реклама
Предупреждения
- Копировать файлы и папки через командную строку довольно рискованно, если вы не знаете, что делаете. Не трогайте папки и файлы, назначение которых вам неизвестно.
Реклама
Об этой статье
Эту страницу просматривали 224 808 раз.
Была ли эта статья полезной?
The `copy` command in Windows Command Prompt is used to duplicate files from one location to another, allowing users to easily manage and back up their data.
Here’s a simple example of how to use the `copy` command:
copy C:\source\file.txt D:\destination\file.txt
Understanding Windows CMD
What is CMD?
CMD, short for Command Prompt, is a command-line interpreter in Windows that allows users to execute commands for managing files and running applications. It offers a text-based interface to interact with the operating system, often used by professionals and power users for its efficiency.
Basic Navigation in CMD
To start using the copy command in windows cmd, you first need to navigate through CMD.
-
Opening CMD: You can open CMD by pressing `Win + R`, typing `cmd`, and hitting `Enter`. Alternatively, you can search for «Command Prompt» in the Start menu.
-
Basic CMD Commands Overview: Familiarize yourself with basic commands that help in navigation:
- `cd` (change directory) to navigate between folders.
- `dir` to list files and directories in the current folder.
Copy Folder Windows Cmd: A Quick How-To Guide
How to Use the Copy Command in CMD
Syntax of the Copy Command
The copy command in cmd operates following a simple syntax:
copy [source] [destination]
- Source: This is the path to the file you want to copy.
- Destination: This is the path where you want to place the copied file.
Examples of the Copy Command in CMD
Copying a Single File
To copy a single file, you would use:
copy C:\source\file.txt C:\destination\
This command copies `file.txt` from the `C:\source` directory to the `C:\destination` directory.
Copying Multiple Files
You can also copy multiple files using wildcards:
copy C:\source\*.txt C:\destination\
This command copies all `.txt` files from the `C:\source` directory to the `C:\destination` directory, which is useful for bulk file management.
Copying Files with Different Extensions
If you want to copy files of a specific type, use the wildcard for their extension:
copy C:\source\*.jpg C:\destination\
This example will copy all JPEG files from the source folder to the destination, showcasing the flexibility of the copy command in windows cmd.
Mastering Pwd in Windows Cmd: Your Quick Reference Guide
Advanced Features of the Copy Command
Overwriting Existing Files
By default, if a file with the same name exists in the destination folder, CMD will prompt you for a decision. To force the command to overwrite without asking, use the `/Y` switch:
copy /Y C:\source\file.txt C:\destination\
This command makes it easier to automate file transfers without interruptions.
Creating Backup Copies
When working with important files, creating backup versions is vital. You can specify a new name for the copied file to keep copies organized:
copy C:\source\file.txt C:\destination\file_backup.txt
This command creates a backup of `file.txt` and saves it as `file_backup.txt` in the destination, ensuring version control.
Using Command Line Parameters
CMD offers various command line parameters for enhanced usability. Some useful parameters include:
- `/V`: Verifies each new file after copying to ensure it was copied correctly.
- `/N`: Uses short filenames if available.
Here’s an example using the `/V` parameter:
copy /V C:\source\file.txt C:\destination\
This command will verify that `file.txt` has been copied correctly, providing an extra layer of assurance.
Cmd Commands Windows 10 Repair: Your Quick Guide
Common Errors and Troubleshooting
Common Issues When Using the Copy Command
It’s crucial to be aware of common errors that might occur while using the copy command cmd windows.
-
File Not Found Error: This error appears when the specified source file does not exist.
- Solution: Double-check the file’s path and ensure the filename is correct.
-
Permission Denied Error: This error may occur if your user account does not have the necessary permissions to access the target folder.
- Solution: Run CMD as an administrator by right-clicking the CMD icon and selecting «Run as administrator.»
How to Check File Paths
Before executing commands, it’s essential to verify your current directory and file paths:
- Showing Current Directory: Use the `cd` command alone:
cd
This command displays the path of your current working directory, helping you locate files accurately.
- Listing Files in a Directory: To view all files and folders in your current directory, use:
dir
This command lists the contents of the current folder, ensuring the files you need are present.
Mastering SCP in Windows Cmd: Quick Transfer Guide
Using Copy Command in Scripts
Automating Copy Tasks
To streamline tasks that involve the copy command in cmd, you can create a batch file. This is a script file that allows the execution of multiple commands. Here’s a simple example:
@echo off
copy C:\source\*.txt C:\destination\
This batch file, when run, will copy all `.txt` files from the `C:\source` directory to `C:\destination`.
Real-world Application Scenarios
The power of the copy command in cmd is evident in real-world applications:
- Backing Up Important Files: Regularly copying files to a backup location ensures data safety.
- Organizing Files from Various Directories: You can use the command to consolidate files into a single folder for easier access and management.
Repair Windows Cmd: Quick Fixes and Tips
Conclusion
Understanding how to effectively use the copy command in windows cmd is invaluable for anyone looking to enhance their productivity or manage files efficiently within the Windows environment. By practicing these commands and leveraging the advanced features, users can significantly optimize their file management tasks.
Call to Action
To continue honing your command-line skills, consider subscribing for more tips and tricks on using CMD effectively. Explore related articles to deepen your understanding and become a CMD expert!
Указанные при описании команды 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 — не нужен.