Как создать каталог в каталоге в командной строке 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


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?

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.

Команда MKDIR используется для создания каталога или подкаталога. Команда имеет следующий синтаксис: MKDIR[диск:]путь. Как видно из синтаксиса команда, параметр «путь» является обязательным. Данный параметр определяет название создаваемого каталога.

Например, создадим на диске «C» папку «MyFolder»: mkdir MyFolder

mkdir

Теперь загляните на диск «C». Если вы все сделали правильно, в корневой директории появится папка «MyFolder». В данном случае мы создали папку в текущей директории. Теперь создадим папку «MyFolder1» на диске «D»: mkdir d:MyFolder

mkdir.

Теперь на диске «D» есть папка «MyFolder1»
Если необходимо создать подкаталог, то используются те же самые команды с указанием всех подкаталогов.
Например, создадим папку «мир», которая находится в папке «привет», которая в свою очередь находится на диске «C»: mkdir приветмир

mkdir..

Теперь, если вы зайдете на диск «C», то увидите там папку «привет», а в этой папке – папку «мир». Таким способом можно создавать подкаталоги, уровень вложенности которых ограничен лишь объемом памяти жесткого диска.
Команда MKDIR не сработает, если вы попытаетесь создать каталог, который уже существует в выбранной директории.
Например, создадим на диске «D» еще одну папку с названием «MyFolder1»

mkdir...

Команда RMDIR удаляет каталог или подкаталог. Cинтаксис команды: RMDIR[/S][Q][диск:]путь.
Например, удалим с диска «D», созданную ранее папку «MyFolder1»: rmdir d:MyFolder1

rmdir

Команда RMDIR не будет выполнена, если в удаляемом каталоге находятся другие каталоги или файлы.
Например, удалим папку «привет» с диска «C» (если не забыли, в этой папке содержится еще одна папка «мир»): rmdir привет
rmdir.Для того чтобы удалить каталог вместе со всеми подкаталогами и файлами используются ключ /S или /Q
При использовании ключа /S команда RMDIR удалит каталог вместе со всем содержимым. При удалении на экран будет выведено сообщение  о подтверждении удаления.  rmdir /S привет

rmdir..На экран выводится сообщение. При нажатии на клавишу «y» папка «привет» удалится вместе со всем содержимым.
Параметр /Q отключает запрос на подтверждение удаления непустого каталога: rmdir /S /Q привет

rmdir...

Обратите внимание, что в данном случаем в одной команде используется сразу 2 ключа. Ключ /S позволяет удалять каталог вместе со всем содержимым, а ключ /Q отключает запрос на подтверждение удаления.

Команду MKDIR можно записать как MD. Обе команды аналогичны друг и являются сокращениями от англ. «make directory» — создать каталог.

Команду RMDIR можно записать как RD. Обе команды аналогичны друг и являются сокращениями от англ. «remove directory» — удалить каталог.


Предыдущая статья: Команда смены текущего каталога CD.
Оглавление: Командная строка.
Следующая статья: Команда COPY для копирования одного или нескольких файлов.


Понравилась статья? Поделить с друзьями:
  • Как создать каталог в cmd windows
  • Как создать исключения в windows defender
  • Как создать исключение в защитнике windows 10
  • Как создать имя учетной записи windows 10
  • Как создать иконку этот компьютер на windows 10