Windows cmd copy file to directory


Download Article


Download Article

Do you need to copy and paste files or folders without using the File Explorer? While navigating the file system with Windows Command Prompt (cmd) might seem daunting, it’s actually pretty easy once you get the hang of it. This wikiHow will teach you how to copy one or more files from one folder to another from the command line in Windows.

  1. Image titled Copy Files in Command Prompt Step 1

    1

    Find out your file’s location. You’ll need the file’s location—also known as a «directory»—in order to tell Command Prompt where to look for the file.

    • You can find the file’s directory by going to the file’s location in File Explorer and then clicking the URL bar near the top of the File Explorer window.
    • Most files will be somewhere in the following directory: [drive letter]:\Users\[username] (for example, «C:\Users\Kyle»). This is the directory in which almost every user-created file on your computer is located.
    • A file on your desktop for the above example would be in the «C:\Users\Kyle\Desktop» directory, while a file in the Documents folder would be in the «C:\Users\Kyle\Documents» directory.
  2. Image titled Copy Files in Command Prompt Step 2

    2

    Know your file’s name. If you want to copy your file, you’ll need to know its name. Keep in mind that file names are case-sensitive in Command Prompt, so you’ll need to include the proper capitalization.

    Advertisement

  3. Image titled Copy Files in Command Prompt Step 3

    3

    Open Start

    Windows Start

    . Click the Windows logo in the bottom-left corner of the screen.[1]

  4. Image titled Copy Files in Command Prompt Step 4

    4

    Type in command prompt. Doing so will search your computer for the Command Prompt program.[2]

  5. Image titled Copy Files in Command Prompt Step 5

    5

    Click

    Windows cmd

    Command Prompt. It’s at the top of the Start window. Doing so will open the Command Prompt program.[3]

    • Keep in mind that if you’re on a shared computer (e.g., a school or public PC), you may not be able to access the Command Prompt.
  6. Advertisement

  1. Image titled Copy Files in Command Prompt Step 6

    1

    Enter the «change directory» command. Type in cd followed by a space, but don’t press Enter.[4]

  2. Image titled Copy Files in Command Prompt Step 7

    2

    Type in your file’s directory. Enter the directory in which the file that you want to copy is located.

  3. Image titled Copy Files in Command Prompt Step 8

    3

    Press Enter. Doing so will reset Command Prompt to look in the entered directory.

  4. Image titled Copy Files in Command Prompt Step 9

    4

    Enter the «copy» command. Type in copy followed by a space, but don’t press Enter yet.[5]

  5. Image titled Copy Files in Command Prompt Step 10

    5

    Enter your file’s name. Type in your file’s name followed by a space, making sure to include the file’s extension (e.g., .txt) for a text file. Don’t press Enter after doing so.[6]

    • If there are spaces in the file’s name, you need to put quotation marks around them. For example, a file named «Pickles are Good.txt» would be Pickles" "are" "Good.txt in Command Prompt.
  6. Image titled Copy Files in Command Prompt Step 11

    6

    Enter a destination directory. Type in another directory (e.g., C:\Users\[you]\Desktop into which you want to copy the file.

    • If you don’t do this, the file will be copied to your user directory (e.g., «C:\Users\[you]») by default.
  7. Image titled Copy Files in Command Prompt Step 12

    7

    Press Enter. Doing so will copy the file into your indicated directory. You can view the copied file by going to the directory in question in your computer’s File Explorer.

  8. Advertisement

  1. Image titled Copy Files in Command Prompt Step 13

    1

    Go to the folder’s directory. Type in cd followed by a space, then type in the folder’s directory and press Enter.[7]

    • For example, if you want to copy all of the files inside of a folder called «Example» that’s on your desktop, you’d go to C:\Users\humpb\Desktop here.
  2. Image titled Copy Files in Command Prompt Step 14

    2

    Enter the robocopy command. Type in robocopy and then a space, but don’t press Enter yet.[8]

  3. Image titled Copy Files in Command Prompt Step 15

    3

    Enter a folder’s name. Type in the name of the folder that you want to copy, then add a space. Again, don’t press the Enter key just yet.

    • As with file names, you’ll need to use quotes around any spaces in the folder name.
  4. Image titled Copy Files in Command Prompt Step 16

    4

    Enter a destination. Type in a directory into which you want to copy the folder’s files.

    • If there are lots of files in the folder, this can get messy if you copy them into an unorganized folder since the folder itself won’t be copied with the files.
  5. Image titled Copy Files in Command Prompt Step 17

    5

    Press Enter. Doing so will copy the contents of the folder into your destination folder.

  6. Advertisement

Add New Question

  • Question

    Which command should I use to copy files?

    Community Answer

    Copy «source path» «destination path». For example, you might copy «C:\Users\qclab\Desktop\Stuff.txt» «P:\IT\Confidential». The quotation marks are optional unless you have spaces in your folder or file names. To copy everything in a folder use *.* as the name and extension. For example, copy «C:\Users\qclab\Desktop\Stuff.txt» «P:\IT\Confidential».

  • Question

    Is it possible to move a PDF file from one folder to another and not have it overwrite another file with the same name by having a different date?

    Community Answer

    You’ll have to rename the PDF file prior to moving it, as two files with the same name can’t reside in the same folder.

  • Question

    How can I copy all files from sub directories with a similar name to a different directory?

    Community Answer

    After you do one, press the up key and then change the name, which shouldn’t take up much time.

See more answers

Ask a Question

200 characters left

Include your email address to get a message when this question is answered.

Submit

Advertisement

  • If you want to create a new destination folder for a set of copied files, enter the directory for the destination folder (including the destination folder itself) in conjunction with the «robocopy» command.[9]

  • You can copy all files in a directory by typing copy *[file type] (e.g., copy *.txt).

  • If you copy the Desktop folder’s contents into a new folder, that new folder will be renamed to «Desktop».

Thanks for submitting a tip for review!

Advertisement

  • Copying files and folders within Command Prompt is potentially dangerous if you don’t know what you’re doing. Never copy or manipulate any files or folders that you don’t understand.

Advertisement

About This Article

Article SummaryX

1. Type «cd» followed by a space in command prompt, but don’t press «enter» yet.
2. Type the name of the directory your filed is located in.
3. Press «enter.»
4. Type «copy» followed by a space, but don’t press «enter.»
5. Type your file’s name followed by a space, but don’t press «enter.»
6. Type in the name of the directory you want to copy the file to.
7. Press «enter» to copy the file.

Did this summary help you?

Thanks to all authors for creating a page that has been read 2,256,826 times.

Is this article up to date?

При работе в командной строке (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 статей о ремонте компьютеров, работе с программами, настройке операционных систем.

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

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

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

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.

What is the windows command prompt command to copy files?

I need to move a file from location A to location B. Also if the folder for location B doesn’t’ exists I want to have it created.

I need this to be a command line so I can automate it.

The version of Windows is XP.

asked May 5, 2009 at 12:50

David Basarab's user avatar

David BasarabDavid Basarab

1,1575 gold badges16 silver badges20 bronze badges

1

The command xcopy is what you are looking for. Example:

xcopy source destination /E /C /H /R /K /O /Y

The command above will copy source to destination, files and directories (including empty ones), will not stop on error, will copy hidden and system files, will overwrite read only files, will preserve attributes and ownership/ACL information, and will suppress the prompting for overwrite existing destination files.

/E    Copies directories and subdirectories, including empty ones.
      Same as /S /E. May be used to modify /T.
/C    Continues copying even if errors occur.
/H    Copies hidden and system files also.
/R    Overwrites read-only files.
/K    Copies attributes. Normal Xcopy will reset read-only attributes.
/O    Copies file ownership and ACL information.
/Y    Suppresses prompting to confirm you want to overwrite an
      existing destination file.

For more info type xcopy /? and your command line.

KCD's user avatar

KCD

9583 gold badges12 silver badges24 bronze badges

answered May 5, 2009 at 13:21

5

Use md to create the folder (it’s ok if it already exists)

Use copy or move for files, and xcopy for folders

answered May 5, 2009 at 12:52

Dani's user avatar

DaniDani

1,2261 gold badge13 silver badges20 bronze badges

3

Use ROBOCOPY if you’re creating backup scripts. xcopy has been deprecated and will likely be phased out of use in the near future. robocopy can do everything xcopy can. It is also more flexible and reliable. Creating scripts with robocopy will future-proof them.


  1. Use robocopy to easily copy folders. The robocopy command replaces the xcopy command. It can quickly copy entire folders without having to worry about defining the contents. For example, to copy all of the contents of the C:\tools directory to the new folder D:\backup\tools, enter the following:

    robocopy C:\tools D:\backup\tools /e
    

    The /e modifier tells robocopy to include all subdirectories. This includes empty folders.
    robocopy will automatically copy hidden and system files. It will create new directories if they don’t exist at the target location.

  2. Mirror a directory. Mirroring a directory is great for making backups. The mirror option of robocopy will copy all of the contents from the source to the destination. It will then delete anything at the destination that doesn’t exist at the source. This ensures that your backup only has the latest versions of your files. For example, to mirror C:\Users\My Documents to D:\backup\My Documents, enter the following:[4]

    robocopy "C:\Users\My Documents" "D:\backup\My Documents" /mir
    

    This function will preserve all permissions of the original files.

  3. Enable restarting. You may want to include the ability to restart the process in case the connection is severed mid-copy.

    robocopy "C:\Users\My Documents" "D:\backup\My Documents" /z
    
  4. Log the copying process. robocopy allows you to create a log file. This can help you pinpoint problems or generate an archive of what’s been copied.

    robocopy "C:\Users\My Documents" "D:\backup\My Documents" /log+:<filename>.txt
    

    The /log+ modifier will append the existing log file instead of overwriting it. If you’d prefer to just overwrite the old log file, use /log:.txt.

answered Nov 22, 2015 at 21:39

Program-Me-Rev's user avatar

In a batch file:

if not exists locationB\nul mkdir locationB
copy locationA\file locationB

if not exists checks the parameter to see if it exists, but it only works on files. To check for existence of a directory, you need to look for a ‘pseudo-file’ called «nul» — checking for existence of this file will always return true if the directory exists.

The copy line copies the file called file in directory locationA to locationB and names the file the same thing. If you want to rename the file at the same time, you can do that too:

copy locationA\file locationB\newfilename

answered May 5, 2009 at 13:21

Graeme Perrow's user avatar

Graeme PerrowGraeme Perrow

5551 gold badge5 silver badges16 bronze badges

If you want the ability to synchronise the copy and other advanced features (ignore certain folders, only include certain wildcards) then look at robocopy. Included in Vista and beyond, optional (from resource kit tools) in earlier versions.

answered May 5, 2009 at 13:51

Richard's user avatar

RichardRichard

5,3241 gold badge23 silver badges20 bronze badges

1

xcopy will create the directory structure for you. Trick is to use the /I option and throw an asterisk at the end of the file name so xcopy thinks you’re copying multiple files, otherwise it asks you if the target name is the file name you want, or the directory name you want. For example.

xcopy /I c:\<SourceDir>\<SourceFile> c:\<TargetDirThatDoesNOTExist>

I’d also look at RoboCopy, but you need to get it from the resource kit as it’s not in Windows until Vista.

answered May 5, 2009 at 13:21

WaldenL's user avatar

WaldenLWaldenL

1,2581 gold badge14 silver badges26 bronze badges

The above command creates an additional directory level with the name of the source file. So…
xcopy /I srcdir\dir1\dir2\file1.txt* destdir\dir1\dir2\file1.txt results in destdir\dir1\dir2\file1.txt\file1.txt

answered Jun 10, 2015 at 15:25

Jeff's user avatar

1

You must log in to answer this question.

Not the answer you’re looking for? Browse other questions tagged

.

  • Windows cannot start this hardware code 19
  • Windows change public network to private
  • Windows cmd set java home
  • Windows cannot run disk checking on this volume because it is write protected что делать
  • Windows build support il2cpp для unity что такое