Как создать директорию в командной строке windows

Статья о том, как создать каталог (папку) в командной строке Windows 7 или Windows 10. Создание дерева каталогов в CMD.

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

В данном материале мы расскажем о том, как создать каталог (папку) в командной строке операционной системы Windows 7 или Windows 10.

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

В командной строке Windows для создания папок (каталогов) используется команда md или ее аналог mkdir (сокращение от английского make directory). С помощью данной команды можно создать одну или несколько новых папок в указанном каталоге. Также данная команда позволяет за один раз создавать целое дерево каталогов.

Синтаксис команды md выглядит следующим образом:

md [<drive>:]<path>

Где:

<drive>: Указывает на диск, на котором нужно создать новый каталог.
<path> Указывает на путь к новому каталого и его имя. Максимальная длина пути зависит от используемой файловой системы.

Нужно отметить, что синтаксис команд md и mkdir аналогичный и работают они совершенно одинаково. Поэтому вы можете использовать любую из этих команд.

Если вам нужно создать новую папку внутри вашего текущего каталога, то для этого достаточно ввести команду md и через пробел указать название для новой папки. Например, если нам нужно создать папку «MyFolder» в текущем каталоге, то для этого нужно ввести команду:

md MyFolder

Чтобы проверить выполнение можно использовать команду «dir /b», которая покажет список всех вложенных папок и файлов.

Как создать папку

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

md c:MyFolder

указать полный путь к создаваемой папке

Естественно, путь к создаваемой папке может быть любым. Например, команда «md c:tmpMyFolder» создаст «MyFolder» внутри каталога «c:tmp»

путь к создаваемой папке

Но, нужно помнить, что для создания папок в системных каталогах (например, в c:Windows), командная строка должна быть запущенна от имени администратора.

Как создать несколько папок в командной строке

Если нужно создать сразу несколько каталогов, то их можно перечислить после команды md (mkdir) через пробел. Так если ввести команду:

md NewFolder1 NewFolder2 NewFolder3

То в текущем каталоге будут созданы сразу три папки: NewFolder1, NewFolder2 и NewFolder3.

Как создать несколько папок

Естественно, это будет работать и при указании полных путей к всем создаваемым папкам.

Как создать дерево каталогов в командной строке

Также команда md (mkdir) позволяет за один раз создать целое дерево каталогов. Для этого просто вводим команду md и через пробел указываем дерево каталогов, которое нужно создать. Например, если ввести команду:

md Folder1Folder2Folder3

То будет создана папка «Folder1», внутри нее «Folder2» и потом «Folder3».

Как создать дерево каталогов

Для проверки создания дерева каталогов можно использовать команду «tree», которая выводит структуру папок в виде дерева.

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

  • Как открыть скрытую папку в Windows 7
  • Как удалить лишние папки из окна «Этот компьютер» в Windows 10
  • Как изменить дату создания (изменения) файла в его свойствах
  • Как переименовать файл (папку) в командной строке Windows 10, 7
  • Как сделать папку скрытой

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

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

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

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

Программистам часто приходится работать в консоли — например, чтобы запустить тестирование проекта, закоммитить новый код на Github или отредактировать документ в vim. Всё это происходит так часто, что все основные действия с файлами становится быстрее и привычнее выполнять в консоли. Рассказываем и показываем основные команды, которые помогут ускорить работу в терминале под ОС Windows.

Для начала нужно установить терминал или запустить командную строку, встроенную в Windows — для этого нажмите Win+R и введите cmd. Терминал часто встречается и прямо в редакторах кода, например, в Visual Studio Code.

Чтобы ввести команду в консоль, нужно напечатать её и нажать клавишу Enter.

Содержимое текущей папки — dir

Выводит список файлов и папок в текущей папке.

C:content-server>dir
 Том в устройстве C имеет метку SYSTEM
 Серийный номер тома: 2C89-ED9D

 Содержимое папки C:content-server

06.10.2020  00:41    <DIR>          .
06.10.2020  00:37    <DIR>          .circleci
16.07.2020  16:04               268 .editorconfig
16.07.2020  16:04                10 .eslintignore
16.07.2020  16:04               482 .eslintrc
06.10.2020  00:37    <DIR>          .github
16.07.2020  16:04                77 .gitignore
06.10.2020  00:41    <DIR>          assets
06.10.2020  00:41    <DIR>          gulp
16.07.2020  16:10               379 gulpfile.js
16.07.2020  16:10           296 320 package-lock.json
16.07.2020  16:10               751 package.json
16.07.2020  16:04               509 README.md

Открыть файл

Чтобы открыть файл в текущей папке, введите его полное имя с расширением. Например, blog.txt или setup.exe.

Перейти в другую папку — cd

Команда cd без аргументов выводит название текущей папки.

Перейти в папку внутри текущего каталога

C:content-server>cd assets
C:content-serverassets>

Перейти на одну папку вверх

C:content-serverassets>cd ..
C:content-server>

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

c:content-server>cd /d d:/ 
d:>

Чтобы просто изменить диск, введите c: или d:

Больше статей о фронтенде и работе в айти в телеграм-канале.

Создать папку — mkdir или md

Создаём пустую папку code внутри папки html:

d:html>mkdir code
d:html>dir

 Содержимое папки d:html

03.11.2020  19:23    <DIR>           .
03.11.2020  19:23    <DIR>           ..
03.11.2020  19:25    <DIR>           code
               0 файлов              0 байт
               3 папок  253 389 438 976 байт свободно

Создаём несколько пустых вложенных папок — для этого записываем их через косую черту.

d:html>mkdir cssjs
d:html>dir Том в устройстве D имеет метку DATA Серийный номер тома: 0000-0000 Содержимое папки d:html 03.11.2020 19:23 <DIR> . 03.11.2020 19:23 <DIR> .. 03.11.2020 19:25 <DIR> code 03.11.2020 19:29 <DIR> css

Создаётся папка css, внутри которой находится папка js. Чтобы проверить это, используем команду tree. Она показывает дерево папок.

Удалить папку — rmdir или rd

Чтобы удалить конкретную папку в текущей, введите команду rmdir.

d:htmlcss>rmdir js

При этом удалить можно только пустую папку. Если попытаться удалить папку, в которой что-то есть, увидим ошибку.

d:htmlcss>d:html>rmdir css
Папка не пуста.

Чтобы удалить дерево папок, используйте ключ /s. Тогда командная строка запросит подтверждение перед тем, как удалить всё.

d:html>rmdir css /s
css, вы уверены [Y(да)/N(нет)]? y

Показать дерево папок — tree

В любом момент мы можем увидеть структуру папок. Для этого используется команда tree.

d:html>tree
Структура папок тома DATA
Серийный номер тома: 0000-0000
D:.
├───code
└───css
    └───js

Если вы хотите посмотреть содержимое всего диска, введите tree в корне нужного диска. Получится красивая анимация, а если файлов много, то ещё и немного медитативная.

Удаление файла — del или erase

Команда для удаления одного или нескольких файлов.

d:html>del blog.txt

Переименование файла — ren или rename

Последовательно вводим ren, старое и новое имя файла.

d:html>dir
 Содержимое папки d:html

03.11.2020  19:23    <DIR>            .
03.11.2020  19:23    <DIR>            ..
03.11.2020  19:59                 0 blag.txt

d:html>ren blag.txt blog.txt

d:html>dir
 Содержимое папки d:html

03.11.2020  19:23    <DIR>            .
03.11.2020  19:23    <DIR>            ..
03.11.2020  19:59                 0 blog.txt

Команды одной строкой

Очистить консоль — cls

Информация о системе — systeminfo

d:html>systeminfo

Имя узла:                         DESKTOP-6MHURG5
Название ОС:                      Майкрософт Windows 10 Pro
Версия ОС:                        10.0.20246 Н/Д построение 20246
Изготовитель ОС:                  Microsoft Corporation
Параметры ОС:                     Изолированная рабочая станция
Сборка ОС:                        Multiprocessor Free

Информация о сетевых настройках — ipconfig

d:html>ipconfig
Настройка протокола IP для Windows
Адаптер Ethernet Ethernet 2:

   Состояние среды. . . . . . . . : Среда передачи недоступна.
   DNS-суффикс подключения . . . . . :

Список запущенных процессов — tasklist

c:>tasklist

Имя образа                     PID Имя сессии          № сеанса       Память
========================= ======== ================ =========== ============
System Idle Process              0 Services                   0         8 КБ
System                           4 Services                   0     2 688 КБ
Secure System                   72 Services                   0    23 332 КБ
…

Справка по командам — help

Команда help без аргументов выводит список всех возможных команд. help вместе с именем команды выведет справку по этой команде.

d:html>help tree
Графическое представление структуры папок или пути.

TREE [диск:][путь] [/F] [/A]

   /F   Вывод имен файлов в каждой папке.
   /A   Использовать символы ASCII вместо символов национальных алфавитов.

В этой статье приведены не все команды и не все их возможности, но вы всегда можете воспользоваться командой help и узнать о том, что ещё может командная строка.

Как ещё ускорить работу

  • 10 горячих клавиш VS Code, которые ускорят вашу работу
  • Полезные команды для работы с Git
  • Полезные команды для работы с Node. js

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

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

Вызов командной строки

Есть несколько приёмов, которые помогут вам начать работу с командной строкой. Открыть её можно следующим образом:

  1. Найдите в системной папке C:WindowsSystem32 файл cmd.exe, кликните по нему дважды.
  2. В версиях WindowsXP и выше нажмите вместе клавиши Win+R. Откроется системное окно «Выполнить». В строчке наберите cmd, подтвердите действие, нажав ОК.
  3. В Win7, чтобы открыть программу, зайдите в «Пуск» — «Все программы», там найдите «Стандартные», нажав на папку для просмотра, увидите значок с подписью для запуска программы.
  4. В Win7, 10 в «Пуске» впишите внизу в строке поиска («Найти программы и файлы») впишите «командная строка», система покажет программу. В Win8 поиск находится в боковом меню.Командная строка Windows 10

При первом запуске по умолчанию вы находитесь в вашем персональном каталоге. Обычно, это «C:Users<имя пользователя>».

Открываем имеющуюся папку

Чтобы открыть папку, в командной строке необходимо указать путь к ней. Вначале вписываете команду «cd», а затем после пробела адрес, например, “C:ProgramFilesSkype”.

Открываем папку через командную строку

ВАЖНО. Учтите: если в названиях, входящих в адрес, есть пробелы, весь путь надо заключить в кавычки. Если названия не содержат пробелов, можно кавычки не пропечатывать при этой команде.

Слэш можно применять как прямой, так обратный ( и /). Оба они читаются программой одинаково, выбирайте удобный, привычный для вас.

Если вы не уверены в точном названии, нажмите TAB, затем стрелки вверх/вниз для прокрутки списка. Предположим, что у вас есть папки «helloYou» и «helloMe», расположены они в «C:». Введите команду «C:>cd h», потом дважды нажмите TAB, так вы прокрутите список компонентов, начинающихся на букву «h».

Просмотр содержимого

Чтобы через командную строку увидеть содержимое какой-либо папки, набирается команда «dir», после которой вписывается путь к ней, затем параметры.

Если путь не указать, то на экране выведется список содержимого, где находитесь в это время.

Просмотр содержимого папки

Если не введёте параметры, список будет представлен с пятью столбцами:

  • дата последнего изменения;
  • дата каталога;
  • если название в списке относится к папке, будет стоять <DIR>; если это другой формат, будет пустое место;
  • вес файла/папки;
  • количество документов в каталоге, их суммарный вес.

Чтобы избежать детализации, введите команду с параметром «/d» — увидите просто список без дополнительной информации.

Создание

Чтобы появилась новая папка, набирается «mkdir», можно сокращённо просто «md». Далее записывается путь к ней, название. Например, в корне диска C вам нужно в имеющемся «Test» создать подпапку «Russian», значит, набираете последовательно «mkdir “C:TestRussian ”».

Команда для создания папки

Можно сразу создать несколько новых папок, укажите пути тогда через пробел либо названия. Допустим, в той же «Test» требуются подпапки 1, 2, 3. Если вы уже находитесь в корне C-диска, наберите «mkdir “Test 1” “Test 2” “Test 3”». Если вы находитесь уже в «Test», можно применять сокращённый вариант команды: «mkdir 1 2 3». Но не забудьте: при наличии пробелов в названиях, их нужно будет заключить в кавычки.

Удаление

Удалить папки, их содержимое позволяет команда «rmdir» либо её сокращённая версия «rm». После прописываются параметры, затем путь.

Если требуется удалить пустой каталог «Example folder», пишется по образцу «rmdir “C: Example folder”».

Удаление папки «Test»

Если «Example folder» не пустой, в нём имеются подпапки/файлы, чтобы всё вместе удалить, следует после команды прописать ключ «/s». Ключ вписывается после «rmdir», но до адреса назначения. То есть запись будет выглядеть так: «rmdir /s “C:Example folder”». Набрав команду, увидите запрос на подтверждение действий, выбираете «y», что значит, что вы согласны удалить («yes»).

Чтобы запрос на подтверждение постоянно не появлялся, можно сразу прописать ключ «/q». Он вписывается после «/s».

Можно перечислить через пробел удаляемое. Допустим, внутри «Test» вам стали не нужны папки 2 и 3, значит, записываете команду: «rmdir /s /q “C:Test1” “C:Test2” “C:Test3”». Если вы уже находитесь в каталоге «Test», можно вписать сокращённый вариант: «rmdir /s /q 1 2 3».

Команда «rmdir /s /q 1 2 3»

Перемещение, переименование

Для этих двух действий существует одна команда — «move». После неё записываются параметры, затем путь к перемещаемой/переименованной папке, затем путь к новообразуемой. Получается, что для перемещения указываете вначале старый путь, затем после пробела место, куда должен каталог переместиться. При переименовании вы указываете путь со старым названием, затем после пробела новое имя.

Рассмотрим на примерах.

  1. Требуется переместить «Foto» из каталога «MyFile» в корень «C:». Прописывается в командной строке следующее: «move “C:MyFileFoto” “C:”».Перемещение «Example folder», которая лежит в каталоге C:Test, в корневую директорию диска «C»
  2. Требуется переименовать «Foto» в «MyFoto». Пишем так: «move “C:MyFileFoto” “My Foto”».Переименуем папку «Example folder» в папку с названием «New example folder»

Переходы

Работая через командную строку, вы захотели перейти в другой каталог. Вам поможет команда «chdir», позволяющая перейти в другое место. Либо просто заходите в раздел, как описывалось в этой статье выше, с помощью команды «cd».

Для перехода в подкаталог, необязательно указывать полный адрес, ежели находитесь в родительском. Допустим, вы находитесь в «ProgramFile», как в командной строке перейти в папку «Skype»? Не нужно указывать полный путь: «cd “C:ProgramFilesSkype”»; достаточно указать название подкаталога: «cd “Skype”».

Чтобы перейти назад, в родительский каталог, вписываем «cd “ProgramFiles”».

Если требуется поменять диск нахождения, добавляется ключ «/D», например, из диска C: понадобилось перейти в D:, прописываете «cd /D d:/».

Копирование

Саму папку формально копировать нельзя, но разрешается скопировать содержимое её, для чего служит команда «xcopy». После неё вписываются параметры, затем адрес копируемого каталога, затем после пробела адрес нового каталога.

Допустим, имеется папка «Foto», понадобилось её скопировать вместе с содержимым из «MyFile» в «NB». Записываем команду так: «xcopy /e “C:MyFileFoto” “C:NBFoto”». Ключ «/e» даёт команду скопировать внутреннее содержимое «Foto».

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


Download Article


Download Article

Learning how to do simple file management at the Command Prompt (cmd) comes in handy when you’re learning to code. When you create files and folders at the command line, you can access, use, and manipulate those folders and files in Windows apps. We’ll show you how to create folders (directories) and text files at the Windows Command Prompt, and teach you commands for deleting unneeded files and folders.

  1. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 10

    1

    Open the Command Prompt. The easiest way to do this is to press Win + S to activate the search bar, type cmd, and then click Command Prompt in the search results.

  2. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 11

    2

    Go to the directory in which you want to create the file. The prompt will open to C:UsersYourName by default. If the directory is somewhere else, type cd path_to_directory and press Enter. Replace path_to_directory with the actual directory location.[1]

    • For example, if you want to create a file on the Desktop, type cd desktop and press Enter.
    • If the directory you’re looking for isn’t in your user directory (e.g., C:UsersYourName), you’ll have to type in the whole path (e.g., C:UsersSomeoneElseDesktopFiles).

    Advertisement

  3. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 12

    3

    Create an empty file. If you don’t want to create an empty file, skip to the next step.[2]
    To create an empty file:

    • Type type nul > filename.txt.
    • Replace filename.txt with whatever you want to call your new file. The «.txt» part indicates that this is a plain text file. Other common file extensions include «.docx» (Word document), «.png» (empty photo),and «.rtf» (rich text document). All of these file types can be read on any Windows computer without installing additional software.
    • Press Enter.
  4. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 13

    4

    Create a file containing certain text. If you don’t want to create a file with certain text inside, skip to the next step.[3]
    Use these steps to create a plain text file that you can type into:

    • Type copy con testfile.txt, but replace testfile with the desired file name.[4]
    • Press Enter.
    • Type some text. This is a rudimentary text editor, but it’s good for quick notes or code. You can use the Enter key to go to the next line.
    • Press Control + Z when you’re finished editing the file.
    • Press the Enter key. You’ll see «1 file(s) copied,» which means your file is now saved with the name you created.
    • Another way to do this is to run this command: echo enter your text here > filename.txt.
  5. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 14

    5

    Create a file that’s a certain size. If you don’t want to create a file that’s a specific size, skip this step.[5]
    To create a blank text file based on byte size, use this command:

    • fsutil file createnew filename.txt 1000.
    • Replace filename with the desired file name, and 1000 with the actual number of bytes you’d like the file to be.
  6. Advertisement

  1. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 15

    1

    Open the Command Prompt. The easiest way to do this is to press Win + S to activate the search bar, type cmd, and then click Command Prompt in the search results.

  2. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 16

    2

    Go to the directory containing the file you want to delete. The prompt will open to C:UsersYourName by default. If the file is somewhere else, type cd path_to_directory and press Enter. Replace path_to_directory with the actual directory location.

    • For example, if you want to delete a file from the Desktop, type cd desktop and press Enter.
    • If the directory you want to view isn’t in your user directory (e.g., C:UsersYourName), you’ll have to type in the whole path (e.g., C:UsersSomeoneElseDesktopFiles).
  3. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 17

    3

    Type dir and press Enter. This displays a list of all files in the current directory. You should see the file you want to delete in this list.

    • Using Command Prompt to delete files results in the files being deleted permanently rather than being moved to the Recycle Bin. Exercise caution when deleting files via Command Prompt.
  4. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 18

    4

    Type del filename and press Enter. Replace filename with the full name and extension of the file you want to delete.[6]
    File names include file extensions (e.g., *.txt, *.jpg). This deletes the file from your computer.

    • For example, to delete a text file entitled «hello», you would type del hello.txt into Command Prompt.
    • If the file’s name has a space in it (e.g., «hi there»), you will place the file’s name in quotations (e.g., del "hi there").
    • If you get an error that says the file cannot be deleted, try using del /f filename instead, as this force-deletes read-only files.
  5. Advertisement

  1. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 1

    1

    Open the Command Prompt. The easiest way to do this is to press Win + S to activate the search bar, type cmd, and then click Command Prompt in the search results.[7]

  2. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 2

    2

    Go to the directory in which you want to create the new directory. The prompt will open to C:UsersYourName by default. If you don’t want to create a new directory here, type cd path_to_directory and press Enter. Replace path_to_directory with the actual directory location.[8]

    • For example, if you want to create a directory on your Desktop, you would type in cd desktop and press Enter.
    • If the directory you’re looking for isn’t in your user directory (e.g., C:UsersYourName), you’ll have to type in the whole path (e.g., C:UsersSomeoneElseDesktopFiles).
  3. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 3

    3

    Type mkdir NameOfDirectory at the prompt. Replace NameOfDirectory with the name of the directory you wish to create.[9]

    • For example, to make a directory named «Homework», you would type mkdir Homework.
  4. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 4

    4

    Press Enter. This runs the command to create a folder with the desired name.

  5. Advertisement

  1. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 5

    1

    Open the Command Prompt. The easiest way to do this is to press Win + S to activate the search bar, type cmd, and then click Command Prompt in the search results.[10]

  2. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 6

    2

    Go to the folder containing the directory you want to delete. The prompt will open to C:UsersYourName by default. If the directory you want to delete is somewhere else, type cd path_to_directory and press Enter.[11]
    Replace path_to_directory with the actual directory location.

    • For example, if you want to delete a directory from your Desktop, type cd desktop.
    • If the directory isn’t in your user directory (e.g., C:UsersYourName), you’ll have to type in the whole path (e.g., C:UsersSomeoneElseDesktopFiles).
  3. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 7

    3

    Type rmdir /s DirectoryName. Replace DirectoryName with the name of the directory you want to delete.[12]

    • For example, if you’re trying to delete your «Homework» folder, you’d type in rmdir /s Homework here.
    • If the directory’s name has a space in it (e.g., «Homework assignments»), place the name in quotations (e.g., rmdir /s "Homework assignments").
  4. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 8

    4

    Press Enter to run the command.[13]

    • If you try to delete a directory that contains hidden files or directories, you’ll see an error that says «The directory is not empty.» In this case, you’ll have to remove the «hidden» and «system» attributes from the files inside the directory. To do this:[14]

      • Use cd to change into the directory you want to delete.
      • Run dir /a to view a list of all files in the directory and their attributes.
      • If you’re still okay with deleting all of the files in the directory, run attrib -hs *. This removes special permissions from the undeletable files.
      • Type cd .. and press Enter to go back one directory.
      • Run the rmdir /s command again to delete the folder.
  5. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 9

    5

    Press y and then Enter to confirm. This will permanently remove the directory.[15]

  6. Advertisement

Add New Question

  • Question

    How can I create directories?

    Subhodeep Roy

    Subhodeep Roy

    Community Answer

    If you are creating a directory in C drive, the command will be»C:MD {the name of the directory/folder}» then press Enter.

  • Question

    How do I create a folder using CMD?

    Community Answer

    Navigate to where you want the subfolder created and type «mkdir «.

  • Question

    How do I create a test file under the sub folder?

    Community Answer

    Change directory into the new sub folder and then on the next line, create your new test file. For example: cd mysubfolder $ type nul > newtextfile.txt

See more answers

Ask a Question

200 characters left

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

Submit

Advertisement

Video

Thanks for submitting a tip for review!

  • Using Command Prompt to delete files results in the files being deleted permanently rather than being moved to the Recycle Bin. Exercise caution when deleting files via Command Prompt.

Advertisement

About This Article

Article SummaryX

1. Use the mkdir command to create a folder.
2. Use rmdir /s to delete a folder.
3. Use the copy con or echo command to create a file.
4. Use del to delete a file.
For tips on how to create a file inside a folder, read on!

Did this summary help you?

Thanks to all authors for creating a page that has been read 1,204,738 times.

Is this article up to date?


Download Article


Download Article

Learning how to do simple file management at the Command Prompt (cmd) comes in handy when you’re learning to code. When you create files and folders at the command line, you can access, use, and manipulate those folders and files in Windows apps. We’ll show you how to create folders (directories) and text files at the Windows Command Prompt, and teach you commands for deleting unneeded files and folders.

  1. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 10

    1

    Open the Command Prompt. The easiest way to do this is to press Win + S to activate the search bar, type cmd, and then click Command Prompt in the search results.

  2. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 11

    2

    Go to the directory in which you want to create the file. The prompt will open to C:UsersYourName by default. If the directory is somewhere else, type cd path_to_directory and press Enter. Replace path_to_directory with the actual directory location.[1]

    • For example, if you want to create a file on the Desktop, type cd desktop and press Enter.
    • If the directory you’re looking for isn’t in your user directory (e.g., C:UsersYourName), you’ll have to type in the whole path (e.g., C:UsersSomeoneElseDesktopFiles).

    Advertisement

  3. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 12

    3

    Create an empty file. If you don’t want to create an empty file, skip to the next step.[2]
    To create an empty file:

    • Type type nul > filename.txt.
    • Replace filename.txt with whatever you want to call your new file. The «.txt» part indicates that this is a plain text file. Other common file extensions include «.docx» (Word document), «.png» (empty photo),and «.rtf» (rich text document). All of these file types can be read on any Windows computer without installing additional software.
    • Press Enter.
  4. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 13

    4

    Create a file containing certain text. If you don’t want to create a file with certain text inside, skip to the next step.[3]
    Use these steps to create a plain text file that you can type into:

    • Type copy con testfile.txt, but replace testfile with the desired file name.[4]
    • Press Enter.
    • Type some text. This is a rudimentary text editor, but it’s good for quick notes or code. You can use the Enter key to go to the next line.
    • Press Control + Z when you’re finished editing the file.
    • Press the Enter key. You’ll see «1 file(s) copied,» which means your file is now saved with the name you created.
    • Another way to do this is to run this command: echo enter your text here > filename.txt.
  5. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 14

    5

    Create a file that’s a certain size. If you don’t want to create a file that’s a specific size, skip this step.[5]
    To create a blank text file based on byte size, use this command:

    • fsutil file createnew filename.txt 1000.
    • Replace filename with the desired file name, and 1000 with the actual number of bytes you’d like the file to be.
  6. Advertisement

  1. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 15

    1

    Open the Command Prompt. The easiest way to do this is to press Win + S to activate the search bar, type cmd, and then click Command Prompt in the search results.

  2. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 16

    2

    Go to the directory containing the file you want to delete. The prompt will open to C:UsersYourName by default. If the file is somewhere else, type cd path_to_directory and press Enter. Replace path_to_directory with the actual directory location.

    • For example, if you want to delete a file from the Desktop, type cd desktop and press Enter.
    • If the directory you want to view isn’t in your user directory (e.g., C:UsersYourName), you’ll have to type in the whole path (e.g., C:UsersSomeoneElseDesktopFiles).
  3. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 17

    3

    Type dir and press Enter. This displays a list of all files in the current directory. You should see the file you want to delete in this list.

    • Using Command Prompt to delete files results in the files being deleted permanently rather than being moved to the Recycle Bin. Exercise caution when deleting files via Command Prompt.
  4. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 18

    4

    Type del filename and press Enter. Replace filename with the full name and extension of the file you want to delete.[6]
    File names include file extensions (e.g., *.txt, *.jpg). This deletes the file from your computer.

    • For example, to delete a text file entitled «hello», you would type del hello.txt into Command Prompt.
    • If the file’s name has a space in it (e.g., «hi there»), you will place the file’s name in quotations (e.g., del "hi there").
    • If you get an error that says the file cannot be deleted, try using del /f filename instead, as this force-deletes read-only files.
  5. Advertisement

  1. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 1

    1

    Open the Command Prompt. The easiest way to do this is to press Win + S to activate the search bar, type cmd, and then click Command Prompt in the search results.[7]

  2. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 2

    2

    Go to the directory in which you want to create the new directory. The prompt will open to C:UsersYourName by default. If you don’t want to create a new directory here, type cd path_to_directory and press Enter. Replace path_to_directory with the actual directory location.[8]

    • For example, if you want to create a directory on your Desktop, you would type in cd desktop and press Enter.
    • If the directory you’re looking for isn’t in your user directory (e.g., C:UsersYourName), you’ll have to type in the whole path (e.g., C:UsersSomeoneElseDesktopFiles).
  3. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 3

    3

    Type mkdir NameOfDirectory at the prompt. Replace NameOfDirectory with the name of the directory you wish to create.[9]

    • For example, to make a directory named «Homework», you would type mkdir Homework.
  4. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 4

    4

    Press Enter. This runs the command to create a folder with the desired name.

  5. Advertisement

  1. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 5

    1

    Open the Command Prompt. The easiest way to do this is to press Win + S to activate the search bar, type cmd, and then click Command Prompt in the search results.[10]

  2. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 6

    2

    Go to the folder containing the directory you want to delete. The prompt will open to C:UsersYourName by default. If the directory you want to delete is somewhere else, type cd path_to_directory and press Enter.[11]
    Replace path_to_directory with the actual directory location.

    • For example, if you want to delete a directory from your Desktop, type cd desktop.
    • If the directory isn’t in your user directory (e.g., C:UsersYourName), you’ll have to type in the whole path (e.g., C:UsersSomeoneElseDesktopFiles).
  3. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 7

    3

    Type rmdir /s DirectoryName. Replace DirectoryName with the name of the directory you want to delete.[12]

    • For example, if you’re trying to delete your «Homework» folder, you’d type in rmdir /s Homework here.
    • If the directory’s name has a space in it (e.g., «Homework assignments»), place the name in quotations (e.g., rmdir /s "Homework assignments").
  4. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 8

    4

    Press Enter to run the command.[13]

    • If you try to delete a directory that contains hidden files or directories, you’ll see an error that says «The directory is not empty.» In this case, you’ll have to remove the «hidden» and «system» attributes from the files inside the directory. To do this:[14]

      • Use cd to change into the directory you want to delete.
      • Run dir /a to view a list of all files in the directory and their attributes.
      • If you’re still okay with deleting all of the files in the directory, run attrib -hs *. This removes special permissions from the undeletable files.
      • Type cd .. and press Enter to go back one directory.
      • Run the rmdir /s command again to delete the folder.
  5. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 9

    5

    Press y and then Enter to confirm. This will permanently remove the directory.[15]

  6. Advertisement

Add New Question

  • Question

    How can I create directories?

    Subhodeep Roy

    Subhodeep Roy

    Community Answer

    If you are creating a directory in C drive, the command will be»C:MD {the name of the directory/folder}» then press Enter.

  • Question

    How do I create a folder using CMD?

    Community Answer

    Navigate to where you want the subfolder created and type «mkdir «.

  • Question

    How do I create a test file under the sub folder?

    Community Answer

    Change directory into the new sub folder and then on the next line, create your new test file. For example: cd mysubfolder $ type nul > newtextfile.txt

See more answers

Ask a Question

200 characters left

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

Submit

Advertisement

Video

Thanks for submitting a tip for review!

  • Using Command Prompt to delete files results in the files being deleted permanently rather than being moved to the Recycle Bin. Exercise caution when deleting files via Command Prompt.

Advertisement

About This Article

Article SummaryX

1. Use the mkdir command to create a folder.
2. Use rmdir /s to delete a folder.
3. Use the copy con or echo command to create a file.
4. Use del to delete a file.
For tips on how to create a file inside a folder, read on!

Did this summary help you?

Thanks to all authors for creating a page that has been read 1,204,738 times.

Is this article up to date?


Загрузить PDF


Загрузить PDF

Командная строка — удобный инструмент для быстрого и эффективного выполнения задач в Windows. Это полнофункциональный и часто недооцененный инструмент компьютерной системы. Действия в командной строке осуществляются без мышки, поэтому она идеально подходит для людей, предпочитающих работать за клавиатурой. Из этой статьи вы узнаете, что собой представляет Командная строка и как с ее помощью выполнять базовые задачи. Прочитав данную статью, вам будет намного проще выполнять базовые задачи через Командную строку.

Шаги

  1. Изображение с названием Create and Delete Files and Directories from Windows Command Prompt Step 1

    1

    Запустите Командную строку. Нажмите на меню «Пуск» и найдите строку поиска. Введите в нее «командная строка» или «cmd». Дважды нажмите на Командную строку в списке результатов, чтобы запустить утилиту. По умолчанию Командная строка имеет следующий вид: C:usersUsername>.

  2. Изображение с названием Create and Delete Files and Directories from Windows Command Prompt Step 2

    2

    Создайте новую папку. Воспользуйтесь командой mkdir для создания новой папки. Чтобы создать папку, необходимо ввести «mkdir-> имя папки». В приведенном выше примере новая папка wikihow была создана с помощью команды: mkdir wikihow.

  3. Изображение с названием Create and Delete Files and Directories from Windows Command Prompt Step 3

    3

    Измените текущий активный каталог. Чтобы перейти в другую папку, воспользуйтесь командой «cd», или change directory (изменить каталог). Для этого введите следующее: cd -> название папки. В нашем примере нужно ввести cd wikihow. Как показано на картинке выше, новая строка будет иметь следующий вид: C:usersIvanwikihow>.

  4. Изображение с названием Create and Delete Files and Directories from Windows Command Prompt Step 4

    4

    Проверьте содержимое папки. Чтобы проверить содержимое текущей папки, воспользуйтесь командой dir. Просто введите dir и нажмите Enter, после чего в Командной строке отобразится список содержимого папки.

  5. Изображение с названием Create and Delete Files and Directories from Windows Command Prompt Step 5

    5

    Очистите данные с экрана. Для этого воспользуйтесь командой cls. Просто введите cls и нажмите Enter, чтобы очистить содержимое с экрана. Как показано на примере выше, на экране останется лишь командная строка.

  6. Изображение с названием Create and Delete Files and Directories from Windows Command Prompt Step 6

    6

    Создайте новый файл. Чтобы создать новый файл, введите команду NUL >. Введите NUL > название файла и нажмите Enter, чтобы создать новый пустой файл. В приведенном выше примере было введено NUL> newfile.

  7. Изображение с названием Create and Delete Files and Directories from Windows Command Prompt Step 7

    7

    Создайте еще один файл. Теперь повторите шаг 6, чтобы создать еще один файл. Назовите этот файл newFile1. Для этого необходимо ввести команду NUL> newFile1.

  8. Изображение с названием Create and Delete Files and Directories from Windows Command Prompt Step 8

    8

    Проверьте содержимое папки. Теперь проверьте содержимое папки с помощью команды dir. Как показано на примере сверху, папка wikihow теперь содержит два новых файла: newFile и newFile1.

  9. Изображение с названием Create and Delete Files and Directories from Windows Command Prompt Step 9

    9

    Удалите файлы. Чтобы удалить файлы, воспользуйтесь командой del. Введите del -> название файла, чтобы удалить конкретный файл. Введите del newFile, чтобы удалить файл с названием newFile. Теперь проверьте содержимое папки wikihow и убедитесь, что файл newFile был удален. Очистите данные с экрана командой cls.

  10. Изображение с названием Create and Delete Files and Directories from Windows Command Prompt Step 10

    10

    Переместитесь выше по дереву каталогов. Чтобы выполнить следующий шаг (удалить папку), вам сначала нужно покинуть текущий активный каталог. Для этого воспользуйтесь версией команды для смены папки. Введите команду cd.., чтобы перейти в родительский каталог, не вводя его название. Введите: cd.. как показано на примере выше. Обратите внимание, что в строке теперь написано C:usersBrian>, а это значит, что вы больше не находитесь в папке wikihow.

  11. Изображение с названием Create and Delete Files and Directories from Windows Command Prompt Step 11

    11

    Удалите пустую папку. Чтобы удалить папку, воспользуйтесь командой rmdir. Пока вы находитесь в папке, ее нельзя будет удалить (смотри шаг 10). Если папка пустая (в ней нет файлов), ее можно удалить, просто введя команду rmdir -> имя папки. В нашем примере в папке wikihow все еще находится файл newFile1, так что команда rmdir не сработает. Как показано на примере выше, если папка не пустая, вы получите сообщение об ошибке.

  12. Изображение с названием Create and Delete Files and Directories from Windows Command Prompt Step 12

    12

    Удалите папку с файлами. Чтобы удалить папку, в которой содержатся файлы, воспользуйтесь измененной командой rmdir. Введите команду rmdir /s wikihow. Введите rmdir /s wikihow и нажмите Enter. Появится окно подтверждения удаления папки, введите Y или N. Введите Y, чтобы подтвердить удаление, или N, чтобы отменить его. Когда вы введете Y, папка и все ее содержимое будут удалены из системы.

    Реклама

Советы

  • Команды можно вводить как заглавными, так и строчными буквами.
  • Используйте команду CLS для регулярной очистки экрана. Так вам будет намного удобнее работать.

Реклама

Предупреждения

  • Для работы с командной строкой нужна практика, а также повышенное внимание при удалении или перемещении файлов. Поскольку в командой строке при удалении файлов не бывает предупреждений или второй попытки, убедитесь, что удаляете именно те файлы и что важные документы останутся нетронутыми.

Реклама

Что вам понадобится

  • Компьютер, работающий на операционной системе Windows
  • Клавиатура

Источники

Об этой статье

Эту страницу просматривали 116 264 раза.

Была ли эта статья полезной?

MD — создание папки через cmd

Команда MD (MKDIR) используется для создания папки или подпапки через командную строку. А для удаления папки через командную строку используется утилита RD.

Синтаксис и параметры команды MD

mkdir [диск:]путь, md [диск:]путь, где

  • диск — Диск, на котором будет создана новая папка.
  • путь — Обязательный параметр. Имя и местоположение новой папки. Максимальная длина пути определяется типом файловой системы.
  • /?— Отображение справки в командной строке.

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

Чтобы создать папку 123 на диске С введите: mkdir C:123md

Как создать 100 папок через командную строку?

Постоянные посетители сайта спрашивают у меня — «Как создать 100 папок через кмд?». Отвечаю, это можно сделать как раз используя комнду MD.

Пишем Bat-файл следующего содержания (открываем txt-файл и сохраняем с расширением *.bat)

@echo off
for /l %%i in (1,1,100) do mkdir «C:/%%i»

  • @echo off — запрещает вывод всех команд на экран;
  • for – цикл, выполняет команду указанное количество раз;
  • do – указывает, что делать;
  • %%i – переменная, куда подставляются значения;
  • in(1,1,100) – набор, который раскрывается в последовательность чисел от заданного начала, шага и конца. В нашем случае от 1,2,3,4,5,6,7,8…100.

Начиная осваивать командную строку, создавая .bat или .cmd файлы все интересуются достаточно простыми вопросами через некоторое время, составляют большие сценарии в скриптах.

Сегодня мы рассмотрим простой пример создания папки в командной строке.

Для создания папки в командной строке:

Зайдите в командную строку, нажав для этого сочетание клавиш Win+R – в окне Выполнить напечатайте cmd и нажмите Enter

example run ru

Окно командной строки.

example cmd ru

Кстати ! Открыв окно командной строки, вы увидите путь C:UsersИмя вашего пользователя

Для перемещения по папкам необходимо воспользоваться командой CD.

Если необходимо перейти в корень диска наберите следующую команду:

CD

Окно с примером как это выглядит в командной строке ниже:

example cd program files

В данном примере рассмотрен переход из папки C:Program Files в корень диска C:

Данная команда позволяет выйти из любой папки или папок в корень диска.

Рассмотрим обратный пример перемещения в интересующую нас папку.

Для этого, необходимо напечатать:

CD Имя папки

Пример ниже:

example cd to program files ru

В данном примере мы перемещаемся из корня диска C: в папку С:Program Files

При перемещении в папку, печатая первые буквы названия этой папки, вы можете воспользоваться кнопкой TAB и если папка существует, то система предложит вариант.

Вот так бывает… В статье — «Как создать папку через командную строку ?» мы еще освоили навигацию по папкам в cmd.

Думаю, что будет полезно.

Для навигации по дискам в командной строке необходимо набрать букву диска и поставить после нее двоеточие и нажать кнопку Enter. Пример перехода на диск D: показан ниже:

example drive d ru

Теперь рассмотрим пример создания папки.

Для создания папки используется команда mkdir

Переместившись в нужный Вам каталог напечатайте:

Mkdir Имя вашей папки

Ниже пример:

example mkdir test ru

На изображении – создание папки Test на диске C:

Можно создать папку и вложенные в нее папки:

Mkdir «Имя вашей папкиИмя вложенной папки»

example mkdir 1 2 3 ru

На изображении указан пример создания папки 1 на диске C: с двумя вложенными папками 2 и 3

Результат будет выглядеть как на изображении ниже

example result create 1 2 3 ru

Также, присутствует возможность создания папки из любой в которой вы находитесь папки без перемещения и навигации по папкам.

Пример:

example create new test

Находясь в папке c:123 мы создаем папку на диске C: с именем New Test

Кавычки при создании папок с пробелом обязательны. Если кавычки отсутствуют, то создается папка с первым словом до пробела, в нашем случае New. Попробуйте поэкспериментировать.

Справка по команде mkdir можно получить по ключу /?

mkdir /?

Starting to master the command line or creation .bat,.cmd files are all interested in fairly simple questions moving from the basics and after a while composing large scripts.

Today, we will look at a simple example of creating a folder on the command line.

To create a folder on the command line:

Go to the command prompt by pressing Win+R in the Run window type cmd and press Enter

example run en

Command prompt window.

example cmd en

Attention! When you open a command prompt window, you will see the path C:UsersYou user login

To move through the folders, use the CD command.

If you want to go to the root of the disk, type the following command:

CD

A window with an example of how it looks in the command line below:

example program files en

In this example the transition from the folder C:Program Files in the root of drive C:

This command allows you to exit any folder or folders in the root of the disk.

To move to the folder you need to type:

CD folder Name

The example below:

example cd to program files en

In this example, we move from the root of the C: drive to the folder C:Program Files

When moving to a folder, typing the first letters of the folder name, you can use the TAB button and if the folder exists, the system will offer the option.

Just like this. In the article how to create a folder via the command line, we have mastered folder navigation in cmd.

I think it will be useful.

To navigate through the disks in the command line, type the letter of the disk and put a colon after it and press Enter. An example of this transition on the D: drive are shown below:

example drive d en

Now! Let’s look at an example of creating a folder.

To create a folder, use the mkdir command

After moving to the desired directory, type:

mkdir name of your folder

Below is an example:

example mkdir test en

In this image we are create a Test folder on drive C:

You can create a folder and its subfolders:

mkdir «your folder Namesubfolder Name»

example mkdir 1 2 3 en

This image shows an example of creating folder 1 on disk C: with two subfolders 2 and 3

The result will look like the image below:

example result create 123 en

There is also the ability to create a folder from any folder in which you are without moving and navigating through the folders.

Example:

example mkdir new test en

Located in the folder С:123 we create a folder on the C: drive named New Test

Quotes are required when creating folders with spaces. If there are no quotes, a folder with the first word before the space is created, in our case, New. Try to experiment.

Help for the mkdir command can be obtained with the /? key.

mkdir /?

Понравилась статья? Поделить с друзьями:
  • Как создать детскую учетную запись в windows 10
  • Как создать дерево каталогов на компьютере windows 10
  • Как создать двух пользователей на windows 10
  • Как создать загрузочную флешку mac os через windows
  • Как создать две формы в windows forms