В командной строке windows команда md позволяет

cd, rd, md, help и другие способы ускорить работу в консоли.

Программистам часто приходится работать в консоли — например, чтобы запустить тестирование проекта, закоммитить новый код на 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,203,184 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,203,184 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.

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

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

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

Почему в мире творится такой хаос? Да потому что администратор нашей системы забыл о выполнении своих обязанностей. Или просто потерял список cmd команд от нашего мира. Хотя это несколько оригинальный взгляд на существующий порядок вещей, но, тем не менее, он отражает часть нужной нам правды: с помощью командной строки можно легко навести порядок в своем компьютере:

  • Что такое командная строка
    • Работа с командной строкой в операционной системе Windows
    • Основные команды для работы с файлами и директориями
    • Команды для работы с сетью
    • Еще несколько нужных команд

Командная строка представляет собой наиболее простой инструмент для управления операционной системой компьютера. Управление происходит с помощью целого ряда зарезервированных команд и набора символов текстовой клавиатуры без участия мыши (в операционной системе Windows).

В системах на основе UNIX при работе с командной строкой возможно применение мыши.

Часть команд пришла к нам еще из MS-DOS. Командную строку также называют консолью. Она применяется не только для администрирования операционной системы, но и для управления обычными программами. Чаще всего в такой набор команд включаются наиболее редко употребляемые.

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

В cmd реализована возможность выполнения и создания целых пакетных файлов, представляющих собой определенный порядок выполнения целого ряда команд (сценариев). Благодаря этому их можно использовать для автоматизации выполнения определенных задач (управление учетными записями, архивация данных и другое).

Командной оболочкой Windows для манипуляции и перенаправления команд определенным утилитам и средствам операционной системы является интерпретатор Cmd.exe. Он загружает консоль и перенаправляет команды в понятном для системы формате.

Вызвать консоль в Windows можно несколькими способами:

  • Через утилиту «Выполнить» — для ее запуска нужно задействовать комбинацию клавиш «Win»+ «R». Затем ввести в поле команду cmd и нажать «Ok»;
  • Работа с командной строкой в операционной системе Windows

  • Через меню «Пуск» — переходим во «Все программы» — «Стандартные» — «Командная строка».

Оба способа подразумевают запуск консоли от имени текущего пользователя. То есть со всеми правами и ограничениями, которые наложены на его роль в операционной системе. Для запуска cmd с правами администратора нужно в меню «Пуск» выделить значок программы и в контекстном меню выбрать соответствующий пункт:

Работа с командной строкой в операционной системе Windows - 2

После запуска утилиты можно получить справочную информацию о командах и формате их написания в консоли. Для этого нужно ввести оператор help и нажать на «Enter»:

Наиболее часто употребляемыми являются следующие команды:

  • RENAME – переименование директорий и файлов. Синтаксис команды:

RENAME | REN [диск/путь] исходное имя файла/каталога | конечное имя_файла
Пример: RENAME C:UsersдомашнийDesktoptost.txt test.txt

  • DEL (ERASE) – используется для удаления только файлов, а не каталогов. Ее синтаксис:

DEL | ERASE [метод обработки] [имя_файла]
Пример: Del C:UsersдомашнийDesktoptest.txt/P

Под методом обработки имеется в виду специальный флаг, позволяющий реализовать определенное условие при осуществлении удаления файла. В нашем примере флаг «P» включает вывод диалога разрешения на удаления каждого файла:

Основные команды для работы с файлами и директориями

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

  • MD – позволяет создать папку по указанному пути. Синтаксис:

MD [диск:] [путь]
Пример:
MD C:UsersдомашнийDesktoptest1test2

В примере будет создана подпапка test2 в папке test1. Если одна из корневых папок пути не существует, то она тоже будет создана:

  • RD (RMDIR) – удаление определенной папки или всех директорий по указанному пути. Синтаксис:

RD | RMDIR [ключ_обработки] [диск/путь]
Пример:
rmdir /s C:UsersдомашнийDesktoptest1test2

В примере используется флаг s, который вызовет удаление всей ветви директорий, указанных в пути. Поэтому не стоит без необходимости использовать команду rmdir с этим ключом обработки.

В следующем разделе мы подробно рассмотрим сетевые команды cmd.

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

  • ping – команда служит для мониторинга возможностей сетевого подключения ПК. Удаленному компьютеру отправляется установленное количество пакетов, а затем отправляется им назад. Учитывается время передачи пакетов и процент потерь. Синтаксис:

ping [-t] [-a] [-n счетчик] [-l размер] [-f] [-i TTL] [-v тип] [-r счетчик] [-s счетчик] [{-j список_узлов | -k список_узлов}] [-w интервал] [имя_конечного_ПК]

Пример реализации команды:
ping example.microsoft.com
ping –w 10000 192.168.239.132

В последнем примере cmd ping команды запрос посылается адресату с указанным IP адресом. Интервал ожидания между пакетами составляет 10 000 (10 сек). По умолчанию этот параметр установлен на 4 000:

Команды для работы с сетью

  • tracert – служит для определения сетевого пути к указанному ресурсу путем посыла специального эхо-сообщения через протокол
  • ICMP (Control Message Protocol). После запуска команды с параметрами выводится список всех маршрутизаторов, через которые проходит путь следования сообщения. Первый в списке элемент является первым маршрутизатором со стороны запрашиваемого ресурса.

Синтаксис tracer команды cmd:
tracert [-d] [-h максимальное_число_переходов] [-j список_узлов] [-w интервал] [имя_конечного_ресурса]
Пример реализации:
tracert -d -h 10 microsoft.com

В примере прослеживается маршрут к указанному ресурсу. При этом увеличивается скорость совершения операции за счет применения параметра d, который предотвращает попытки команды получить разрешение на чтение IP адресов. Количество переходов (прыжков) ограничено 10 с помощью установленного значения параметра h. По умолчанию, количество прыжков равно 30:

    Команды для работы с сетью - 2

  • shutdown – используется для перезагрузки, отключения и выхода из сеанса определенного пользователя локальной машины или удаленного ПК. Синтаксис этой cmd команды сети:

shutdown [{-l|-s|-r|-a}] [-f] [-m [имя_ПК]] [-t xx] [-c «сообщения»] [-d[u][p]:xx:yy]
Пример:
shutdown /s /t 60 /f /l /m 191.162.1.53

Произойдет выключение (s) удаленного ПК (m) с указанным IP адресом (191.162.1.53) через 60 секунд (t). При этом принудительно будет выполнен выход из всех приложений (f) и сеанса текущего пользователя (l).

При работе с ПК может пригодиться еще несколько команд из огромного списка операторов cmd. Вот некоторые из них:

  • format – выполняет форматирование CD диска в дисководе, имя которого указано в параметрах. Синтаксис команды:

format том [/fs: Файловая_Система] [/v: метка] [/q] [/a: размер] [/c] [/x]

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

Это подтверждает следующий пример написания команды:
format e: — будет отформатирован носитель в дисководе E;

  • set – служит для работы с переменными среды. Эта cmd команда позволяет создавать, удалять и присваивать значение переменным, которые можно использовать во время работы с командной строкой. Синтаксис:

set [[/a [выражение]] [/p [имя_переменной=]] строка]
Пример:
set include=c:inc

  • start – предназначена для запуска указанной программы или команды в отдельном окне:

Пример:
start notepad

Еще несколько нужных команд

Теперь с багажом полученных знаний можно не то что своим компьютером управлять, но и целой реальностью. Осталось только запустить соответствующий экземпляр cmd. Да и не все описанные в статье команды могут подойти для управления «действующим экземпляром» нашей реальности.

Командная строка: вызов и использование

DOS-команды все еще можно встретить даже во времена пестрых окон и анимированных программ. Вспоминать об этом вы начинаете, например, если возникают проблемы с Windows и вам нужно создать резервную копию данных без помощи графического интерфейса. DOS-окно (в Windows это называется «Командная строка») можно открыть двумя способами:

  • Вызвать из меню «Пуск» в разделе «Все программы» — «Стандартные» (Windows 7) или «Пуск» — «Windows-система» — «Командная строка» (Windows 10).
  • Вызвать из поиска Windows, введя команду «cmd».

Навигация по файловой системе

Навигация по файловой системе в DOS осуществляется с помощью команды cd. Она означает «change directory» (сменить директорию) и может использоваться несколькими способами:

  • Прямой вызов папки, например, с «cd Documents». С помощью этой команды вы перейдете непосредственно в папку «Documents».
  • Вызов «cd». Эта команда вернет вас непосредственно в корневой каталог вашего жесткого диска.
  • Команда «cd» может использоваться в сочетании с командой «dir», которая позволяет просматривать каталоги на жестком диске. С помощью этих двух команд у вас есть возможность перемещаться по всему жесткому диску.
  • Кроме того, «dir» может применяться с параметрами, например «dir /w» и «dir /p», для постраничного просмотра содержимого ваших каталогов. Это рекомендуется для удобства просмотра очень больших каталогов.

Создание, копирование и удаление папок через DOS-команды

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

  • Команда md означает «make directory» и создает новую папку в текущем каталоге, то есть в том, где вы сейчас находитесь. Папка создается с помощью команды «MD [имя каталога]», например «MD Test».
  • Команды del [имя_файла] или «erase [имя_файла]» удаляют файл. Команда rd [имя каталога] удаляет пустой каталог.
  • Команда copy для копирования файлов немного сложнее. Здесь вам нужно указать источник и место назначения с каталогом и именами файлов. Пример: «copy c:testtestdatei.txt c:testdatei.txt». В этом примере будет скопирован файл «testdatei.txt» из папки «c:test» в основной каталог «c:».

Сетевые функции в DOS-окне

Теперь давайте посмотрим на функцию, которую вы, возможно, использовали в Windows в DOS-режиме: определение вашего IP-адреса и сетевых настроек.

  • Вызов команды «ipconfig» позволяет получить текущий IP-адрес, шлюз и подсеть. С помощью команды «ipconfig /all» вы найдете всю подробную информацию, такую как, например, MAC-адрес вашей сетевой карты.
  • Команда Ipconfig также часто используется совместно с командой ping. Она может проверить соединение между двумя компьютерами в сети и вызывается с помощью «ping [имя компьютера]» или «ping [IP-адрес]».
  • Команда «arp -a» перечисляет компьютеры или устройства, с которыми взаимодействовало ваше устройство. Это важно, например, если ваш компьютер подключен к неизвестному маршрутизатору. Таким образом, вы получите IP-адрес роутера и сможете использовать его для доступа в интернет.
  • Если требуется информация о пользователях, может быть полезна команда «finger [Имя_компьютера]». Главное, чтобы ее не блокировал брандмауэр.
  • «Ftp» позволяет отправлять и принимать файлы. Для этого введите «ftp» в командной строке. После этого вы можете ввести дополнительные команды, например, «open host». Это установит соединение с FTP-сервером.

Другие полезные команды

В случае работы с пакетными файлами или скриптами имеет смысл сообщить пользователю о том, что делает скрипт. Для этого подходит команда «echo [сообщение]».
Разделы диска помимо прочего содержат и зашифрованные файлы. Информацию об этом можно получить с помощью команды «cipher /C». Кроме того, файлы можно зашифровать с помощью параметра «/D» или расшифровать с помощью «/E». Однако следует обратить внимание на тот факт, что эта команда для работы с разделами действует только в файловой системе NTFS.

Если вы залогинены на удаленном компьютере, то можете удаленно управлять его выключением с помощью команды: «shutdown /s». При использовании этой же команды с параметром «/r» компьютер будет перезагружен. Параметр «/l» обеспечит выход из текущего сеанса.

Чтобы получить полный обзор DOS-команд, введите в окне DOS команду «help». В результате её выполнения вы увидите все основные команды в виде списка. Подробные сведения об определенных функциях можно также получить с помощью вызова «help [команда]», например «help cd» или «help copy». Также известные со старых добрых времен DOS классические игры вы можете запустить под DOSBox.

Читайте также:

  • Шумит ноутбук или системный блок: что делать?=«content_internal_link»>
  • Windows 7 перестали обновлять: на какую ОС переходить?=«content_internal_link»>

Понравилась статья? Поделить с друзьями:
  • В кодировке windows один символ весит
  • В кодировке windows 1251 шестнадцатеричное представление
  • В кодировке windows 1251 каждый символ кодируется 8 битами вова хотел
  • В кодирование windows 1251 каждый символ кодируется 8 битами
  • В кнопке пуск нет завершения работы windows