Командная строка Windows (CMD) — мощный инструмент, который предоставляет доступ к широкому набору команд для выполнения различных задач, от работы с файлами до настройки сети и автоматизации процессов. В статье рассмотрим 100 популярных команд CMD, которые пригодятся как новичкам, так и опытным пользователям. Для удобства они разделены по категориям.
Разделы
- Общие команды CMD
- Сетевые команды CMD
- Команды для управления процессами
- Команды для управления файловой системой
- Команды для управления пользователями
- Команды для управления безопасностью
- Команды для диагностики и устранения неполадок
- Команды для скриптинга и автоматизации
- Команды для управления сетевыми подключениями
- Команды для управления печатью
- Дополнительные команды в Windows
Общие команды командной строки (CMD) позволяют пользователям управлять ОС Windows через интерфейс командной строки. Они нацелены на различные задачи – от получения справочной информации до управления процессами.
- hel — выводит список всех доступных команд и их краткое описание, что полезно для получения информации о базовых командах.
- cls — очищает экран командной строки. Если в окне CMD много текста, этой командой можно убрать весь вывод и начать работу «с чистого листа».
- exit — завершает текущую сессию командной строки и закрывает окно CMD.
- echo — выводит сообщения в консоль или включает/выключает отображение команд в пакетных файлах – echo Hello, World! выведет Hello, World! на экран.
- ver — отображает версию операционной системы Windows.
- title — изменяет заголовок окна командной строки. Например, title Моя Командная Строка изменит заголовок на «Моя Командная Строка».
- pause — временно приостанавливает выполнение скрипта, но при нажатии любой клавиши можно продолжить работу.
- date — позволяет узнать или изменить текущую дату в системе.
- time — отображает или изменяет текущее время в системе.
- tasklist — выводит список всех запущенных процессов с их PID (идентификатором процесса).
- powercfg — управляет настройками энергопотребления и профилями питания.
- fc — сравнивает два файла и отображает их различия.
Сетевые команды CMD
В разделе собраны основные сетевые команды CMD, которые помогут управлять подключениями, диагностировать сетевые проблемы и выполнять разнообразные операции с сетью. Они незаменимы для системных администраторов и пользователей, нуждающихся в решении сетевых задач.
- ping — проверяет связь с удаленным узлом, отправляя ему пакеты данных. Например, ping google.com проверит доступность сервера Google.
- ipconfig — отображает конфигурацию сетевых интерфейсов системы (IP-адреса, маску подсети и шлюзы).
- netstat — выводит информацию о сетевых соединениях и открытых портах
- netstat -an — показывает все активные соединения.
- tracert — отслеживает маршрут пакета до целевого узла – tracert yandex.ru покажет все узлы, через которые проходит запрос.
- nslookup — используется для проверки информации о DNS-серверах.
- nslookup example.com — отображает IP-адрес сайта example.com.
- arp — выводит или изменяет записи ARP (Address Resolution Protocol) –: arp -a покажет текущие записи ARP.
- route — управляет таблицей маршрутизации сети – route print выведет все существующие маршруты в системе.
- net use — подключает сетевые диски. Например, net use Z: \\server\folder подключит сетевой ресурс как диск Z:.
- netsh — позволяет настраивать различные параметры сети через командную строку.
- netsh wlan show profiles — отображает сохраненные профили Wi-Fi.
Команды для управления процессами
Команды ниже позволяют эффективно управлять процессами и службами на вашем ПК: помогают запускать службы, планировать задачи, управлять активными процессами, а также выключать или перезагружать систему. С их помощью можно автоматизировать выполнение задач, получать информацию о состоянии системы и контролировать её работоспособность.
- sc — управляет службами Windows. Пример: sc start servicename запустит службу с именем servicename.
- schtasks — управляет планировщиком задач. Так, schtasks /create /tn «Моя Задача» /tr notepad.exe /sc once /st 12:00 создаст задачу для запуска.
- start — запускает программу или команду в новом окне. Например, start notepad откроет блокнот.
- wmic — взаимодействует с системой через Windows Management Instrumentation – wmic process list brief покажет список процессов.
- shutdown — выключает, перезагружает или завершает работу системы. Так, shutdown /s /f /t 0 немедленно выключит компьютер.
- systeminfo — выводит информацию о системе, включая версию Windows, параметры оборудования и установленные обновления.
Команды для управления файловой системой
Команды для управления файловой системой в CMD позволяют работать с файлами и папками: просматривать содержимое директорий, перемещаться между папками, создавать и удалять файлы и каталоги, копировать данные с использованием различных опций.
- dir — отображает список файлов и каталогов в указанной директории. Пример: dir C:\Windows выведет содержимое папки Windows.
- cd — меняет текущий каталог. Так, cd C:\Users перейдет в папку пользователей.
- md NewFolder — создает новую папку.
- rd — удаляет пустую папку. Пример: rd NewFolder удалит папку NewFolder.
- copy — копирует файлы из одного места в другое.
- move — перемещает файлы или папки.
- del — удаляет файлы. Например, del file.txt удалит файл file.txt.
- xcopy — копирует файлы и директории, включая их структуру. Так, xcopy C:\Source D:\Destination /s /e скопирует все файлы и папки из Source в Destination.
- robocopy — более продвинутая версия xcopy, используется для надежного копирования данных. Например, robocopy C:\Source D:\Destination /mir синхронизирует две папки.
Команды для управления пользователями
Команды для управления пользователями предоставляют средства для администрирования учетных записей, настройки групповых прав и управления политиками безопасности. А также позволяют администраторам эффективно управлять пользователями в системе, добавлять новых пользователей, изменять их права и настраивать параметры учетных записей.
- net user — управляет учетными записями пользователей.
- net user UserName /add — добавляет нового пользователя с именем UserName.
- net localgroup — управляет локальными группами пользователей.
- net localgroup Administrators UserName /add — добавляет пользователя в группу администраторов.
- whoami — выводит имя текущего пользователя и информацию о его правах.
- runas — позволяет запускать программы от имени другого пользователя. Так, runas /user:administrator cmd запустит CMD с правами администратора.
- net accounts — управляет параметрами учетных записей, например, минимальной длиной пароля и периодом его действия.
- gpupdate — обновляет групповые политики на локальном компьютере, что полезно для администраторов, управляемых сетей.
- taskview — открывает таймлайн Windows, показывая историю активности пользователя, полезно для управления и поиска ранее использованных файлов и приложений.
- msg — отправляет сообщение пользователям, подключенным к системе. Пример: msg «Система будет перезагружена через 5 минут» отправит сообщение всем пользователям.
Команды для управления безопасностью
Команды для управления безопасностью предназначены для обеспечения защиты данных и управления доступом к файлам и системным ресурсам, что позволяет шифровать файлы, проверять целостность системных файлов и управлять правами доступа.
- cipher — управляет шифрованием файлов на дисках NTFS.
- cipher/e — зашифровывает файлы в указанной директории.
- sfc — проверяет целостность системных файлов и автоматически восстанавливает их при обнаружении повреждений.
- sfc /verifyonly — проверяет системные файлы на наличие повреждений, но не исправляет их автоматически.
- sfc /scannow — выполняет полную проверку системы.
- cacls — изменяет права доступа к файлам. Пример: cacls file.txt /g UserName:F даст пользователю полный доступ к файлу.
- icacls — расширяет возможности команды cacls и предоставляет дополнительные параметры для управления правами доступа.
- takeown — позволяет взять владение файлом или директорией. Так, takeown /f file.txt предоставит доступ к файлам.
- attrib — изменяет атрибуты файлов и папок. Например, attrib +r file.txt сделает файл доступным только для чтения.
Команды для диагностики и устранения неполадок
Команды из раздела помогают находить и устранять неполадки в системе, восстанавливать загрузочные параметры и проверять целостность данных на диске, а также они позволяют решать проблемы, связанные с запуском операционной системы или со сбоями на уровне файловой системы.
- chkdsk — проверяет диск на наличие ошибок и исправляет их. Так, chkdsk C: /f выполнит проверку диска C.
- bootrec — восстанавливает загрузочный сектор.
- bcdedit — управляет параметрами загрузки системы.
- bcdedit /set {current} safeboot minimal — включает безопасный режим.
Команды для скриптинга и автоматизации
Команды, приведенные ниже, предназначены для создания сложных сценариев выполнения команд, что позволяет автоматизировать повседневные задачи и более эффективно управлять процессами.
- for — создает цикл для выполнения команд. Например, for %i in (1 2 3) do echo %i выведет числа 1, 2, 3.
- if — выполняет условное выполнение команд.
- goto — перенаправляет выполнение скрипта к определенной метке.
- call — вызывает другую команду или скрипт.
Команды для управления сетевыми подключениями
Команды для управления сетевыми подключениями предоставляют возможности для настройки, диагностики и оптимизации сетевых параметров и соединений, позволяя управлять IP-адресами, подключаться и отключаться от сетей.
- ipconfig /release — освобождает текущий IP-адрес, назначенный DHCP сервером, что позволяет при необходимости сбросить сетевое подключение.
- ipconfig /renew — обновляет IP-адрес, полученный от DHCP сервера. Часто используется после команды ipconfig /release для восстановления подключения.
- ipconfig /flushdns — очищает кэш DNS, если изменился DNS-сервер или необходимо устранить проблемы с доступом к сайтам.
- ipconfig /displaydns — выводит содержимое кэша DNS, часто используется для диагностики проблем с DNS.
- netsh interface ip set address — используется для назначения статического IP-адреса сетевому интерфейсу. Пример: netsh interface ip set address Ethernet static 192.168.1.100 255.255.255.0 192.168.1.1.
- netsh wlan show drivers — выводит информацию о драйверах беспроводной сети, что полезно при настройке Wi-Fi подключения.
- netsh wlan show interfaces — отображает текущие активные беспроводные подключения и их параметры, например, мощность сигнала.
- netsh wlan connect — подключает к указанной Wi-Fi сети. Для этого нужно ввести: netsh wlan connect name=MyWiFi.
- netsh wlan disconnect — отключает текущее беспроводное подключение.
- netsh advfirewall set allprofiles state — управляет состоянием брандмауэра Windows – netsh advfirewall set allprofiles state off отключает брандмауэр для всех профилей.
- netsh int ip reset — сбрасывает настройки IP стека (TCP/IP) к значениям по умолчанию, помогая при сетевых неполадках.
- route add — добавляет маршрут в таблицу маршрутизации. Например, route add 192.168.2.0 mask 255.255.255.0 192.168.1.1 добавит маршрут для подсети 192.168.2.0 через шлюз 192.168.1.1.
- route delete — удаляет указанный маршрут из таблицы маршрутизации.
- netsh interface show interface — выводит список всех сетевых интерфейсов в системе, включая их состояние и тип.
- net view — отображает список компьютеров в локальной сети – net view \\server покажет общие ресурсы на указанном сервере.
- net use /delete — удаляет существующее подключение к сетевому ресурсу. Так, net use Z: /delete отключает сетевой диск Z:.
- ftp — открывает FTP-клиент для передачи файлов между локальной и удаленной системами. Например, по команде ftp ftp.example.com ПК подключится к FTP-серверу.
- telnet — используется для подключения к удаленным системам через Telnet-протокол. Так, telnet example.com 23 подключит ПК к серверу на порту 23.
- getmac — выводит MAC-адреса всех сетевых интерфейсов компьютера.
Команды для управления печатью
В этом разделе команды для управления печатью позволяют эффективно управлять процессом печати (включая очередью на печать), настройками принтеров и заданиями на печать.
- print — отправляет файл на печать. Например, print C:\Documents\file.txt отправит текстовый файл на принтер по умолчанию.
- rundll32 printui.dll,PrintUIEntry — открывает диалоговое окно для установки или управления принтерами – rundll32 printui.dll,PrintUIEntry /in /n\\server\printer установит сетевой принтер.
- net print — отображает список заданий на печать – net print \\server\printer покажет очередь печати на указанном принтере.
- net stop spooler — останавливает службу диспетчера очереди печати (spooler), особенно когда требуется устранить зависшие задания печати.
- net start spooler — запускает службу диспетчера очереди печати после её остановки.
- wmic printer list brief — выводит список установленных принтеров с краткой информацией о каждом из них.
- wmic printer where default=true get name — выводит имя принтера, установленного по умолчанию.
- wmic printer where name=’PrinterName’ delete — удаляет указанный принтер из системы.
- wmic printerconfig — отображает информацию о конфигурации принтера, включая его настройки и параметры печати.
- cscript prnjobs.vbs — используется для управления заданиями печати через скрипт prnjobs.vbs, который можно использовать для удаления, приостановки или возобновления заданий.
Дополнительные команды в Windows
В дополнение к основным инструментам для управления системой, командная строка Windows предоставляет ряд дополнительных команд, которые расширяют возможности администрирования и диагностики.
- wevtutil — управляет журналами событий Windows. Например, wevtutil qe System выведет события из системного журнала.
- tzutil — управляет настройками часовых поясов. tzutil /s Pacific Standard Time установит часовой пояс на Тихоокеанское стандартное время.
- taskkill — завершает процесс по его PID или имени. Так, taskkill /F /PID 1234 завершит процесс с PID 1234.
- powercfg /hibernate off — отключает режим гибернации.
- powercfg /energy — создает отчет об использовании энергии системой.
How to find the size of a file
In Windows, we can use dir command to get the file size.
C:\>dir vlcplayer.exe Directory of C:\ 02/22/2011 10:30 PM 20,364,702 vlcplayer.exe 1 File(s) 20,364,702 bytes 0 Dir(s) 86,917,496,832 bytes free
But there is no option/switch to print only the file size.
Get size for all the files in a directory
Dir command accepts wild cards. We can use ‘*” to get the file sizes for all the files in a directory.
C:\>dir C:\Windows\Fonts Volume in drive C is Windows 7 Volume Serial Number is 14A1-91B9 Directory of C:\Windows\Fonts 06/11/2009 02:13 AM 10,976 8514fix.fon 06/11/2009 02:13 AM 10,976 8514fixe.fon 06/11/2009 02:13 AM 11,520 8514fixg.fon 06/11/2009 02:13 AM 10,976 8514fixr.fon 06/11/2009 02:13 AM 11,488 8514fixt.fon 06/11/2009 02:13 AM 12,288 8514oem.fon 06/11/2009 02:13 AM 13,248 8514oeme.fon 06/11/2009 02:13 AM 12,800 8514oemg.fon
We can also get size for files of certain type. For example, to get file size for mp3 files, we can run the command ‘dir *.mp3‘.
The above command prints file modified time also. To print only the file name and size we can run the below command from a batch file.
@echo off for /F "tokens=4,5" %%a in ('dir c:\windows\fonts') do echo %%a %%b
Save the above commands to a text file, say filesize.bat, and run it from command prompt.
Get directory size
There’s no Windows built in command to find directory size. But there is a tool called diruse.exe which can be used to get folder size. This tool is part of XP support tools. This command can be used to get directory size. This command’s syntax is given below.
diruse.exe directory_name C:\>diruse c:\windows Size (b) Files Directory 12555896050 64206 SUB-TOTAL: C:\WINDOWS 12555896050 64206 TOTAL: C:\WINDOWS
As you can see in the above example, diruse prints the directory size in bytes and it also prints the number of files in the directory(it counts the number of files in the sub folders also)
To get the directory size in mega bytes we can add /M switch.
C:\>diruse /M C:\Windows Size (mb) Files Directory 11974.24 64206 SUB-TOTAL: C:\WINDOWS 11974.24 64206 TOTAL: C:\WINDOWS
Download XP Support Tools
Though the tool is intended for XP and Server 2003, I have observed that it works on Windows 7 also. The above examples were indeed from a Windows 7 computer.
- Use the “DIR” command to list files and folders in the current directory, or “DIR /S” to list files and folders recursively, in subdirectories as well.
- To search for specific file types use the asterisk followed by the file extension type, in this syntax: DIR *.jpg
- Use attribute switches to filter the type of files and folders to list.
It can be tricky to keep tabs on all files and folders on a Windows computer, especially if there are too many. There can be many folders and subfolders inside a partition, and many different types of file extensions. It can be difficult to view all the files and folders, or even search for specific ones using File Explorer.
Using the Command Prompt, you can view and list all sorts of files and folders inside a directory, and even its subdirectories using recursive switches. Not only that, but you can also list all items with a specific file type, or exclude them. Moreover, you can also view hidden items as well directly from the Command Prompt.
In this article, we give you a bunch of different examples to list files and folders inside the Command Prompt using the DIR cmdlet.
Command to List Files and Folders in Command Prompt
The DIR command is used to list files and folders inside a directory in Command Prompt. This command can be used with a number of switches and attributes to filter the items to display, their order or displaying, to include and exclude, and so on.
However, the only switches we will be interested in are /a and /s.
Using the DIR
command alone will display all the files and folders inside that particular directory. It will not show any hidden items, and it will now show any items inside the subdirectories. However, if you use DIR /a
, it will show the hidden items as well.
To perform a recursive search, we must use the /s
switch.
The table below summarises the commands to use to list files and folders and these switches:
Command | Description |
DIR | Display items inside the current directory |
DIR /a | Display all items inside the current directory, including hidden ones. |
DIR /s | List items inside the current directory as well as all subdirectories |
With that known, there is a list of attributes that you can use with the DIR /a
cmdlet to filter the type of information you want to list. Here is a list of the attributes you can use with /a
.
Attribute Alphabet | Description | Syntax Example |
d | Shows directories only | DIR /ad |
h | Show hidden items only | DIR /ah |
s | Show system files only | DIR /as |
l | Show reparse points only | DIR /al |
r | Show read-only files | DIR /ar |
a | Show files that can be archived | DIR /aa |
i | Show files whose content is not indexed | DIR /ai |
– (hyphen) | Used before an attribute to exclude it from the list | DIR /a-s (hide system files) |
: (colon) | To combine multiple attributes | DIR /a:h-s (Show hidden items but hide system files) |
Example Commands to List Files and Folders in Command Prompt
Let us now continue to see more extensive examples with images to better understand how you can list files and folders using the DIR
cmdlet.
-
To list all files and folders in the current directory:
DIR
List files and folders in the current directory using Command Prompt -
To list all files and folders in the current directory and subdirectories:
DIR /S
List recursive files and folders in Command Prompt -
To list only folders in the current directory:
DIR /AD
List only folders in the current directory in Command Prompt -
To list only folders in the current directory and subdirectories:
DIR /AD /S
List only folders in the current directory and subdirectories in Command Prompt -
To list all files in the current directory and exclude all folders:
DIR /A-D
List all files and exclude folders in the current directory in Command Prompt -
To list all hidden system files in the current directory:
DIR /ASH
List all hidden system files in current directory in Command Prompt -
To list all system files and exclude read-only files in the current directory and subdirectories:
DIR /A:S-A /S
List all system files and exclude read-only files in the current directory and subdirectories using Command Prompt -
To list all specific file type files in the current directory and subdirectories:
Note: You can change the file type extension to list the files you are looking for.
DIR *.txt
List all files with a specific file type using Command Prompt -
To list multiple file types in the current directory and subdirectories:
DIR *.txt *.doc *.docx /S
List multiple file types in the current directory and subdirectories from Command Prompt
There can be many different examples and syntaxes to list files and folders inside the Command Prompt. However, we hope that the examples above are sufficient so that you can combine and modify them as per your requirements.
Closing Words
The Windows command line offers much more control over the fetched data than its GUI. Using the Command Prompt, you can list different files and folders inside the current directory as well as its subdirectories. You can also filter out the type of files and folders to include, or exclude from the list.
Программистам часто приходится работать в консоли — например, чтобы запустить тестирование проекта, закоммитить новый код на Github или отредактировать документ в vim. Всё это происходит так часто, что все основные действия с файлами становится быстрее и привычнее выполнять в консоли. Рассказываем и показываем основные команды, которые помогут ускорить работу в терминале под OS 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-server\assets>
Перейти на одну папку вверх:
C:\content-server\assets>cd ..
C:\content-server>
Перейти в папку на другом диске:
c:\content-server>cd /d d:/
d:\>
Чтобы просто изменить диск, введите c:
или d:
.
Создать папку — mkdir или md
Создаём пустую папку code
внутри папки html
:
d:\html>mkdir coded:\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 css\js
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:\html\css>rmdir js
При этом удалить можно только пустую папку. Если попытаться удалить папку, в которой что-то есть, увидим ошибку:
d:\html\css>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
«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.
ТелеграмПодкастБесплатные учебники
The Windows Command Prompt (CMD) is a powerful tool that allows users to interact with their operating system through text-based commands. Whether you’re a beginner exploring CMD for the first time, an expert troubleshooting advanced issues, or just looking for utility-focused tasks, this guide has you covered.
In this guide, we will provide you with some of the most useful commands for the following:
- CMD Commands for Beginners
- CMD Commands for Experts
- CMD Commands for Utility
- CMD Commands for Troubleshooting
- CMD Commands for Students
- CMD Commands for Programmers
CMD Commands for Beginners
These commands are essential for users who are new to CMD and provide basic functionalities to help them navigate and perform simple tasks.
1. View Directory ‘dir
‘
- Function: Displays the contents of the current directory.
- How to use: Type
dir
and press Enter. Usedir /s
to include subdirectories. - Use case: Quickly view files and folders in your current location.
Syntax: dir
2. Change Directories ‘cd’
- Function: Lets you navigate between folders.
- How to use: Type
cd [folder_name]
to move into a directory. Usecd ..
to go up one level. - Use case: Navigate to specific directories to manage files or execute commands
Syntax: cd [folder name]
3. Create a New Directory ‘mkdir’ or ‘md’
- Function: Allows you to create a new directory
- How to use: Type mkdir [file_name]– Here the new directory name is GFG
- Use case: When you need a new directory for any separate work, you may create a new directory
Syntax: mkdir [GFG]
4. Rename a File ‘ren’
- Function: Helps in renaming any file or directory.
- How to use: Type
ren
or
rename [old_name] [new_name]
and press Enter. - Use case: Discover new method of renaming file or any directory.
Syntax: ren xyz.txt newxyz.txt
5. Delete a File ‘del’
- Function: Lets you to remove one or more files
- How to use: Type del [file_name]– This will erase the provided file name
- Use case: This function allows you to erase any file if you’re unable to fetch
Syntax: del[file_name]
6. Close ‘exit’
- Function: Closes the Command Prompt window.
- How to use: Type
exit
and press Enter. - Use case: Ends your session with CMD.
Syntax: exit
7. Clear Screen ‘cls’
- Function: Clears all text from the CMD window.
- How to use: Type
cls
and press Enter. - Use case: Removes clutter after multiple commands
Syntax: cls
8. View Available Command ‘help’
- Function: Lists all available commands and their descriptions.
- How to use: Type
help
and press Enter. - Use case: Discover new commands and learn their functions.
Syntax: help
9. Display or Set the System time ‘time’
- Function: Lets you set the system time or display the current time.
- How to use: Type
t
ime [new_time] and press Enter. - Use case: Allows the user to set their system’s time without additional navigation
Syntax: time [new_time]
10. Copy Files ‘copy’
- Function: Lists all available commands and their descriptions.
- How to use: Type
c
opy [source1] [destination2] and press Enter. - Use case: Discover new commands and learn their functions.
Syntax: copy file.txt Backup\
Command | Description | Syntax | Example |
---|---|---|---|
dir |
View the contents of a directory | dir |
dir C:\Users\Documents |
cd |
Change the current working directory | cd [directory_name] |
cd Downloads |
mkdir |
Create a new directory | mkdir [directory_name] |
mkdir NewProject |
ren |
Rename a file | ren [old_name] [new_name] |
ren draft.txt final.txt |
del |
Delete a file | del [file_name] |
del unwanted.txt |
exit |
Close the Command Prompt | exit |
exit |
cls |
Clear the Command Prompt screen | cls |
cls |
help |
View available CMD commands and their descriptions | help |
help |
time |
Display or set the system time | time |
time 14:30:00 |
copy |
Copy files from one location to another | copy [destination] |
copy report.docx D:\Backup\ |
CMD Commands for Experts
These commands are more advanced and suitable for users comfortable with troubleshooting and system management tasks.
1. System File Checker ‘sfc’
- Function: Scans and repairs corrupted system files.
- How to use: Type
sfc /scannow
in CMD (run as administrator). - Use case: Fix system errors related to missing or corrupted files.
Syntax: sfc /scannow
2. Disk Error ‘chkdsk’
- Function: Scans the hard drive for bad sectors and file system errors.
- How to use: Type
chkdsk [drive letter]
: /f
(e.g.,chkdsk C: /f
) in CMD. - Use case: Identify and fix disk issues.
Syntax: chkdsk C: /f
3. View Running Processor ‘tasklist’
- Function: Displays all running processes and their details.
- How to use: Type
tasklist
to list processes. Usetasklist /fi "imagename eq [process name]"
to filter. - Use case: Identify resource-heavy or unresponsive processes.
Syntax: tasklist /fi "imagename eq [process name]
4. Restart ‘shutdown’
- Function: Allows you to shut down or restart the computer via CMD.
- How to use:
- Shutdown:
shutdown /s /f /t [seconds]
. - Restart:
shutdown /r /f /t [seconds]
.
- Shutdown:
- Use case: Automate shutdown or restart tasks
Syntax:
Shutdown: shutdown /s /f /t [seconds].
Restart: shutdown /r /f /t [seconds].
5. Network Statistics ‘netstat’
- Function: Displays active connections and listening ports.
- How to use: Type
netstat
to view all active connections. - Use case: Diagnose network-related issues or monitor network activity.
Syntax: netstat
6. Kill a Running Process ‘taskkill’
- Function: Lets you terminate a process using its process ID (PID)
- How to use: Type
t
askkill /[PID] /F to terminate - Use case: Can be helpful for terminating any dedicated PID.
Example (PID: 1124)
Syntax: taskkill /PID 11234 /F
7. View Saved Passwords ‘netsh wlan show profiles’
- Function: Retrieve the password of a saved Wi-Fi network.
- How to use: Type netsh wlan show profile name=”WiFi-Name” key=clear
- Use case: Discover new commands and learn their functions.
Example: netsh wlan show profile name="MyHomeWiFi" key=clear
Command | Description | Syntax | Example |
---|---|---|---|
sfc |
System File Checker – Scans and repairs system files | sfc /scannow |
sfc /scannow |
chkdsk |
Check Disk – Scans and fixes disk errors | chkdsk [drive]: /f /r |
chkdsk C: /f /r |
tasklist |
View running processes | tasklist |
tasklist |
shutdown |
Shutdown or restart the system | shutdown /r /t [seconds] |
shutdown /r /t 10 (Restart in 10 seconds) |
netstat |
View network statistics and active connections | netstat -a |
netstat -an (Show all connections numerically) |
taskkill |
Kill a running process using its process ID (PID) | taskkill /PID [PID] /F |
taskkill /PID 4567 /F (Kill process with ID 4567) |
netsh wlan show profiles |
View saved Wi-Fi network names | netsh wlan show profiles |
netsh wlan show profiles |
CMD Commands for Utility
These commands are focused on specific tasks and utilities to enhance productivity and system performance.
1. Network Configuration ‘ipconfig’
- Function: Displays IP address, subnet mask, and gateway information.
- How to use:
- Basic: Type
ipconfig
. - Detailed: Type
ipconfig /all
.
- Basic: Type
- Use case: Troubleshoot internet connectivity issues.
Syntax: ipconfig
2. Network Connectivity ‘ping’
- Function: Sends packets to test communication with another device or website.
- How to use: Type
ping
[destination]
- Use case: Check if a device or website is reachable.
Syntax: ping geeksforgeeks.org
3. System Information ‘systeminfo’
- Function: Displays detailed information about your computer.
- How to use: Type
systeminfo
. - Use case: Quickly access system specifications for troubleshooting or reporting.
Syntax: systeminfo
4. Trace Route ‘tracert’
- Function: Shows the path packets take to reach a specific destination.
- How to use: Type
tracert
[destination]
- Use case: Identify network bottlenecks or connectivity issues.
Syntax: tracert geeksforgeeks.org
5. Manage Drives ‘diskpart’
- Function: Opens a command-line utility for managing disk partitions.
- How to use: Type
diskpart
to enter the disk management interface. - Use case: Create, delete, or modify partitions on your drives.
Syntax: diskpart
6. Delete a Directory ‘rmdir’
- Function: Removes directory from the origin
- How to use: Type rmdir [directory_name] and press Enter.
- Use case: Discover new commands and learn their functions.
Example: GFG – Directory name
Syntax: rmdir GFG
7. View ‘rmdir’
- Function: Removes directory from the origin
- How to use: Type rmdir [directory_name] and press Enter.
- Use case: Discover new commands and learn their functions.
Example: GFG - Directory name
8. Manage User Account ‘net user’
- Function: To list all the user accounts
- How to use: Type net user and press Enter.
- Use case: Discover new commands and learn their functions.
Syntax: net user username password /add
9. View Startup Programs ‘wmic startup get caption,command’
- Function: To check what programs launch on startup.
- How to use: Type wmic startup get caption,command, and press Enter.
- Use case: Discover new commands and learn their functions.
Syntax: wmic startup get caption,command
Command | Description | Syntax | Example |
---|---|---|---|
ipconfig |
View network configuration, including IP address, subnet mask, and gateway | ipconfig |
ipconfig /all (Displays detailed network info) |
ping |
Test network connectivity by sending packets to a host | ping [host or IP] |
ping google.com (Check connection to Google) |
systeminfo |
Display detailed system information, including OS version, installed memory, and processor | systeminfo |
systeminfo |
tracert |
Trace the route packets take to a network destination | tracert [hostname or IP] |
tracert google.com (View network path to Google) |
diskpart |
Manage disk partitions, including creating, formatting, and deleting partitions | diskpart |
diskpart → list disk → select disk 1 → create partition primary |
rmdir |
Delete a directory (folder) | rmdir [directory_name] |
rmdir /s /q OldFolder (Delete a folder and its contents without confirmation) |
dir |
View contents of a directory | dir |
dir C:\Users\Documents (List files in a specific directory) |
net user |
Manage user accounts, including adding, modifying, or deleting users | net user |
net user John password123 /add (Create a new user account) |
wmic startup get caption,command |
View startup programs and their commands | wmic startup get caption,command |
wmic startup get caption,command |
CMD Commands for Troubleshooting
1. File Comparison ‘fc’
- Function: Compares two files and highlights differences.
- How to use: Type
fc [file1] [file2]
to compare files. - Use case: Detect changes or errors in files
Syntax: fc 1 2
2. Advanced Network Diagnostics ‘pathping’
- Function: Combines
ping
andtracert
functionalities to provide detailed network path diagnostics. - How to use: Type
pathping
[destination]
- Use case: Troubleshoot complex network issues.
Syntax: pathping geeksforgeeks.org
3. Registry Editor ‘regedit’
- Function: Launches the Windows Registry Editor.
- How to use: Type
regedit
to open the registry. - Use case: Modify registry keys for advanced configuration or troubleshooting.
Syntax: regedit
4. View MAC ‘getmac’
- Function: Displays the MAC address of your network adapter.
- How to use: Type
getmac
to view the MAC address. - Use case: Identify your device’s hardware address for network configurations
Syntax: getmac
5. Power Configuration ‘powercfg’
- Function: Displays and manages power settings.
- How to use: Type
powercfg
/[option]
- Use case: Optimize power usage and troubleshoot battery issues.
Syntax: powercfg /energy
for a detailed power usage report
6. Enable Boot Manager ‘bcdedit’
- Function: Used to modify boot configuration settings
- How to use: Type
bcdedit
/ set current
- Use case: Discover new commands and learn their functions.
Syntax: bcdedit /set {current} bootmenupolicy standard
7. Format a Drive ‘format’
- Function: To erase any specific drive.
- How to use: Type format [drive]: /FS:NTFS and press Enter.
- Use case: Discover new commands and learn their functions.
Syntax: format D: /FS:NTFS
Command | Description | Syntax | Example |
---|---|---|---|
fc |
Compare two files and highlight differences | fc [file1] [file2] |
fc file1.txt file2.txt (Compare two text files) |
pathping |
Perform advanced network diagnostics with packet loss details | pathping [destination] |
pathping google.com (Analyze network route to Google) |
regedit |
Open the Windows Registry Editor (GUI) | regedit |
regedit (Opens the registry editor – use with caution!) |
getmac |
Display the MAC (Media Access Control) address of your network adapters | getmac |
getmac /v /fo list (View MAC addresses in detailed format) |
powercfg |
Manage and analyze power configurations | powercfg /[option] |
powercfg /batteryreport (Generate a battery usage report) |
bcdedit |
Enable, disable, or modify Windows Boot Configuration | bcdedit /set {current} [option] |
bcdedit /set {current} bootmenupolicy standard (Enable boot menu in Windows 10/11) |
format |
Format a drive (erase all data) | format [drive]: /FS:[filesystem] |
format D: /FS:NTFS (Format drive D: with NTFS file system) |
CMD Commands for Students
Students can use these commands to manage files, perform simple calculations, and even help with tasks like coding and studying.
1. Calculator ‘calc’
- Function: Opens the Windows Calculator application.
- How to use: Type
calc
and press Enter. - Use case: Quickly open the calculator for
Syntax: calc
CMD Commands for Programmers
Programmers often use CMD to automate tasks, compile code, and test network functionality. These commands can be especially useful for developers working in command-line environments.
1. Compile Java Code ‘javac’
- Function: Compiles Java source files into bytecode.
- How to use: Type
javac [file name].java
to compile Java code. - Use case: Compile and test Java programs directly from the command line.
Syntax: javac
2. Version Control ‘git’
- Function: Interacts with Git repositories from the command line.
- How to use: Type
git [command]
- Use case: Manage version control, clone repositories, or push commits from the command line.
Syntax: git clone [repository URL]
3. Execute Python Script ‘python’
- Function: Runs Python scripts in the command prompt.
- How to use: Type
python [script.py]
to execute a Python program. - Use case: Test and run Python code directly in the command line.
Syntax: python [script.py]
4. Run Node.js Scripts ‘node’
- Function: Executes Node.js scripts.
- How to use: Type
node [script.js]
to run a JavaScript file using Node.js. - Use case: Run backend scripts and test JavaScript programs in the command line.
Syntax: node [script.js]
5. Node Package Manager ‘npm’
- Function: Installs and manages JavaScript packages.
- How to use: Type
npm install [package]
to install a package. - Use case: Manage dependencies and libraries in Node.js applications.
Syntax: npm install [package]
Command | Description | Syntax | Example |
---|---|---|---|
javac |
Compile Java source code into bytecode (.class files) | javac [filename].java |
javac HelloWorld.java (Compile a Java file) |
git |
Version control system for tracking changes in files | git [command] |
git clone https://github.com/user/repo.git (Clone a repository) |
python |
Execute a Python script or enter interactive mode | python [script.py] |
python script.py (Run a Python script) |
node |
Execute JavaScript code using Node.js | node [script.js] |
node app.js (Run a Node.js script) |
npm |
Manage Node.js packages and dependencies | npm [command] |
npm install express (Install the Express.js package) |
Bonus: CMD Tricks and Tips
To make CMD usage even more efficient, here are some bonus tips:
1. Save CMD Output to a File
Use the >
operator to save the output of a command to a text file.
2. Open CMD in a Specific Directory
Instead of navigating manually, you can directly open CMD in a folder by typing cmd
in the File Explorer’s address bar.
3. Use &&
for Multiple Commands
You can run multiple commands sequentially:
ipconfig && ping google.com
Conclusion
Mastering the most useful CMD commands in Windows can empower you to perform tasks more efficiently, troubleshoot problems, and gain deeper control over your system. By familiarizing yourself with these essential CMD commands, you’ll be better equipped to handle a variety of situations, from simple file management to advanced system configurations. Whether you’re a beginner or an experienced user, these commands are invaluable tools to have at your disposal.