From Wikipedia, the free encyclopedia
For other uses, see CMD.
«Command Prompt» redirects here. For the concept, see Command prompt.
Command Prompt (cmd.exe)
Other names | Windows Command Processor |
---|---|
Developer(s) | Microsoft, IBM, ReactOS contributors |
Initial release | December 1987; 37 years ago |
Operating system |
|
Platform | IA-32, x86-64, ARM (and historically DEC Alpha, MIPS, PowerPC, and Itanium) |
Predecessor | COMMAND.COM |
Type | Command-line interpreter |
Command Prompt, also known as cmd.exe or cmd, is the default command-line interpreter for the OS/2,[1] eComStation, ArcaOS, Microsoft Windows (Windows NT family and Windows CE family), and ReactOS[2] operating systems. On Windows CE .NET 4.2,[3] Windows CE 5.0[4] and Windows Embedded CE 6.0[5] it is referred to as the Command Processor Shell. Its implementations differ between operating systems, but the behavior and basic set of commands are consistent. cmd.exe is the counterpart of COMMAND.COM in DOS and Windows 9x systems, and analogous to the Unix shells used on Unix-like systems. The initial version of cmd.exe for Windows NT was developed by Therese Stowell.[6] Windows CE 2.11 was the first embedded Windows release to support a console and a Windows CE version of cmd.exe.[7] The ReactOS implementation of cmd.exe is derived from FreeCOM, the FreeDOS command line interpreter.[2]
cmd.exe interacts with the user through a command-line interface. On Windows, this interface is implemented through the Win32 console. cmd.exe may take advantage of features available to native programs of its own platform. For example, on OS/2 and Windows, it can use real pipes in command pipelines, allowing both sides of the pipeline to run concurrently. As a result, it is possible to redirect the standard error stream. (COMMAND.COM uses temporary files, and runs the two sides serially, one after the other.)
Multiple commands can be processed in a single command line using the command separator &&.[8]
When using this separator in the Windows cmd.exe, each command must complete successfully for the following commands to execute. For example:
C:\>CommandA && CommandB && CommandC
In the above example, CommandB will only execute if CommandA completes successfully, and the execution of CommandC depends on the successful completion of CommandB. To process subsequent commands even if the previous command produces an error, the command separator & should be used.[9] For example:
C:\>CommandA & CommandB & CommandC
On Windows XP or later, the maximum length of the string that can be used at the command prompt is 8191 (213-1) characters. On earlier versions, such as Windows 2000 or Windows NT 4.0, the maximum length of the string is 2047 (211-1) characters. This limit includes the command line, individual environment variables that are inherited by other processes, and all environment variable expansions.[10]
Quotation marks are required for the following special characters:[8]
& < > [ ] { } ^ = ; ! ' + , ` ~
and white space.
The following is a list of the Microsoft OS/2 internal cmd.exe commands:[11]
- break
- chcp
- cd
- chdir
- cls
- copy
- date
- del
- detach
- dir
- dpath
- echo
- erase
- exit
- for
- goto
- if
- md
- mkdir
- path
- pause
- prompt
- rd
- rem
- ren
- rename
- rmdir
- set
- shift
- start
- time
- type
- ver
- verify
- vol
The following list of internal commands is supported by cmd.exe on Windows NT and later:[12]
- assoc
- break
- call
- cd
- chdir
- cls
- color
- copy
- date
- del
- dir
- dpath
- echo
- endlocal
- erase
- exit
- for
- ftype
- goto
- help
- if
- keys
- md
- mkdir
- mklink (introduced in Windows Vista)
- move
- path
- pause
- popd
- prompt
- pushd
- rd
- rem
- ren
- rename
- rmdir
- set
- setlocal
- shift
- start
- time
- title
- type
- ver
- verify
- vol
The following list of commands is supported by cmd.exe on Windows CE .NET 4.2,[13] Windows CE 5.0[14] and Windows Embedded CE 6.0:[15]
- attrib
- call
- cd
- chdir
- cls
- copy
- date
- del
- dir
- echo
- erase
- exit
- goto
- help
- if
- md
- mkdir
- move
- path
- pause
- prompt
- pwd
- rd
- rem
- ren
- rename
- rmdir
- set
- shift
- start
- time
- title
- type
In addition, the net command is available as an external command stored in \Windows\net.exe.
The ReactOS implementation includes the following internal commands:[2]
- ?
- alias
- assoc
- beep
- call
- cd
- chdir
- choice
- cls
- color
- copy
- ctty
- date
- del
- delete
- delay
- dir
- dirs
- echo
- echos
- echoerr
- echoserr
- endlocal
- erase
- exit
- for
- free
- goto
- history
- if
- memory
- md
- mkdir
- mklink
- move
- path
- pause
- popd
- prompt
- pushd
- rd
- rmdir
- rem
- ren
- rename
- replace
- screen
- set
- setlocal
- shift
- start
- time
- timer
- title
- type
- ver
- verify
- vol
Comparison with COMMAND.COM
[edit]
On Windows, cmd.exe is mostly compatible with COMMAND.COM but provides the following extensions over it:
- More detailed error messages than the blanket «Bad command or file name» (in the case of malformed commands) of COMMAND.COM. In OS/2, errors are reported in the chosen language of the system, their text being taken from the system message files. The HELP command can then be issued with the error message number to obtain further information.
- Supports using of arrow keys to scroll through command history. (Under DOS this function was only available under DR DOS (through HISTORY) and later via an external component called DOSKEY.)
- Adds rotating command-line completion for file and folder paths, where the user can cycle through results for the prefix using the Tab ↹, and ⇧ Shift+Tab ↹ for reverse direction.
- Treats the caret character (^) as the escape character; the character following it is to be taken literally. There are special characters in cmd.exe and COMMAND.COM that are meant to alter the behavior of the command line processor. The caret character forces the command line processor to interpret them literally.
- Supports delayed variable expansion with
SETLOCAL EnableDelayedExpansion
, allowing values of variables to be calculated at runtime instead of during parsing of script before execution (Windows 2000 and later), fixing DOS idioms that made using control structures hard and complex.[16] The extensions can be disabled, providing a stricter compatibility mode.
Internal commands have also been improved:
- The DELTREE command was merged into the RD command, as part of its /S switch.
- SetLocal and EndLocal commands limit the scope of changes to the environment. Changes made to the command line environment after SetLocal commands are local to the batch file. EndLocal command restores the previous settings.[17]
- The Call command allows subroutines within batch file. The Call command in COMMAND.COM only supports calling external batch files.
- File name parser extensions to the Set command are comparable with C shell.[further explanation needed]
- The Set command can perform expression evaluation.
- An expansion of the For command supports parsing files and arbitrary sets in addition to file names.
- The new PushD and PopD commands provide access past navigated paths similar to «forward» and «back» buttons in a web browser or File Explorer.
- The conditional IF command can perform case-insensitive comparisons and numeric equality and inequality comparisons in addition to case-sensitive string comparisons. (This was available in DR-DOS, but not in PC DOS or MS-DOS.)
- Comparison of command shells
- List of DOS commands
- COMMAND.COM
- PowerShell
- Windows Terminal
- ^ «Notes on using the default OS/2 command processor (CMD.EXE)». www.tavi.co.uk.
- ^ a b c «reactos/reactos». GitHub. December 4, 2021.
- ^ «Command Processor Shell (Windows CE .NET 4.2)». Microsoft Docs. June 30, 2006. Archived from the original on August 31, 2022.
- ^ «Command Processor Shell (Windows CE 5.0)». Microsoft Docs. September 14, 2012. Archived from the original on August 28, 2022.
- ^ «Command Processor Shell (Windows Embedded CE 6.0)». Microsoft Docs. 2012. Archived from the original on September 5, 2022.
- ^ Zachary, G. Pascal (1994). Showstopper! The Breakneck Race to Create Windows NT and the Next Generation at Microsoft. The Free Press. ISBN 0-02-935671-7.
- ^ Douglas McConnaughey Boling (2001). Programming Microsoft Windows CE (2nd ed.). Microsoft Press. ISBN 978-0735614437.
- ^ a b «cmd». Microsoft Learn. September 12, 2023. Archived from the original on November 21, 2023.
- ^ «Command Redirection, Pipes — Windows CMD — SS64.com». ss64.com. Retrieved September 23, 2021.
- ^ Command prompt (Cmd.exe) command-line string limitation
- ^ Microsoft Operating System/2 User’s Reference (PDF). Microsoft. 1987.
- ^ Hill, Tim (1998). Windows NT Shell Scripting. Macmillan Technical Publishing. ISBN 978-1578700479.
- ^ «Command Processor Commands (Windows CE .NET 4.2)». Microsoft Docs. June 30, 2006. Archived from the original on August 31, 2022.
- ^ «Command Processor Commands (Windows CE 5.0)». Microsoft Docs. September 14, 2012. Archived from the original on August 31, 2022.
- ^ «Command Processor Commands (Windows Embedded CE 6.0)». Microsoft Docs. January 5, 2012. Archived from the original on September 6, 2022.
- ^ «Windows 2000 delayed environment variable expansion». Windows IT Pro. Archived from the original on July 13, 2015. Retrieved July 13, 2015.
- ^ «Setlocal». TechNet. Microsoft. September 11, 2009. Retrieved January 13, 2015.
- David Moskowitz; David Kerr (1994). OS/2 2.11 Unleashed (2nd ed.). Sams Publishing. ISBN 978-0672304453.
- Stanek, William R. (2008). Windows Command-Line Administrator’s Pocket Consultant (2nd ed.). Microsoft Press. ISBN 978-0735622623.
- «Command-line reference A-Z». Microsoft. April 26, 2023.
- «Cmd». Microsoft Windows XP Product Documentation. Microsoft. Archived from the original on September 2, 2011. Retrieved May 24, 2006.
- «Command Prompt: frequently asked questions». windows Help. Microsoft. Archived from the original on April 22, 2015. Retrieved April 20, 2015.
- «An A–Z Index of the Windows CMD command line». SS64.com.
- «Windows CMD.com – Hub of Windows Commands». windowscmd.com. Archived from the original on January 11, 2022. Retrieved January 4, 2022.
- Most important CMD commands in Windows — colorconsole.de
Сегодня, когда пользователь при управлении компьютером чаще полагается на графический интерфейс (GUI), командная строка может показаться немного устаревшей. Однако не стоит спешить с выводами! С помощью командной строки можно ускорить выполнение типовых задач и автоматизировать их, а также получить данные, которые обычно скрыты от пользователя, например, информацию о скорости отклика сайтов и так далее. В нашем материале мы расскажем подробнее о командной строке, как использовать ее для выполнения различных задач и какие команды можно взять на вооружение обычному пользователю.
Что такое командная строка — определение
Командная строка — это интерфейс, который позволяет пользователям взаимодействовать с компьютером, вводя текстовые команды. Ее также называют интерфейсом командной строки, а на английском название звучит как CLI или Command Line Interface. В различных источниках этот инструмент можно увидеть под названиями «консоль», «терминал», cmd и так далее.
Внешний вид интерфейса командной строки в операционной системе Windows
С помощью командной строки можно взаимодействовать с файлами, как в проводнике. Но некоторые задачи с помощью командной строки Windows пользователь может решить быстрее и эффективнее. Главное преимущество использования командной строки — автоматизация некоторых задач, вроде копирования файлов, удаления ненужных объектов и так далее. Кроме того, она предоставляет доступ к большому количеству утилит и инструментов, у которых может не быть графического интерфейса.
Несмотря на широкие возможности, которые предоставляет командная строка, не каждый владелец компьютера знает, как ее использовать. Она требует знания специфического синтаксиса и команд. Однако, познакомившись с общей информацией по теме и немного попрактиковавшись, вы сможете освоить этот инструмент и автоматизировать часть рутинных задач, экономя время и повышая производительность своей работы.
Для чего используют командную строку в Windows
Как уже говорилось, возможности командной строки достаточно широки. Но для чего именно она может понадобиться вам? Составим список типичных задач, для которых используется командная строка Windows:
- Управление файлами и папками. Командная строка позволяет создавать, перемещать, копировать и удалять файлы и папки, а также изменять их атрибуты. Например, можно создать новую папку, переместить файлы из одной папки в другую, а после удалить ненужную директорию.
- Управление процессами. Командная строка предоставляет возможность просматривать активные процессы на компьютере, запускать новые процессы и завершать их. Например, можно запустить программу из командной строки или завершить процесс, который перестал отвечать.
- Управление сетью. С помощью командной строки можно настраивать сетевые параметры, проверять подключение к сети, выполнять пинги и трассировки маршрута. Это может быть полезно для диагностики сетевых проблем или настройки сетевых соединений.
- Автоматизация задач. Командная строка позволяет создавать скрипты и пакетные файлы для автоматизации повторяющихся задач. Например, можно написать скрипт, который будет копировать определенные файлы в заданную папку.
- Работа с базами данных. Командная строка предоставляет возможность взаимодействовать с базами данных, выполнять запросы, создавать таблицы и управлять данными. Это может быть полезно для анализа данных или автоматизации операций с базами.
Список команд для командной строки Windows обширен и разнообразен. Перечисленные возможности — далеко не полный набор функций, что становится доступен пользователю, освоившему работу через Command Line Interface.
Два вида командной строки: CMD и PowerShell
Интерпретатор командной строки (Command Line Interpreter, или CMD) и PowerShell — это два похожих на первый взгляд инструмента, которые позволяют пользователям напрямую взаимодействовать с операционной системой.
CMD является традиционным инструментом командной строки в операционных системах Windows уже много лет. Он предоставляет базовый набор команд для управления файлами, папками и другими системными ресурсами. CMD основан на командной оболочке MS-DOS, предлагает множество функций, но и имеет ограниченные возможности сценариев и не поддерживает множество современных технологий.
CMD и PowerShell — интерфейсы похожи, но инструменты разные
PowerShell, с другой стороны, является более мощным и гибким инструментом командной строки. Он предоставляет расширенные возможности, интегрируется с различными технологиями и API. PowerShell основан на платформе .NET Framework и поддерживает множество командлетов (cmdlets), которые представляют собой маленькие программы, специально разработанные для выполнения конкретных задач. Командлеты PowerShell могут использоваться для автоматизации задач, управления системными ресурсами, работы с реестром, сетевым взаимодействием и многим другим.
Несмотря на широкие возможности PowerShell, у большинства по умолчанию стоит именно классическая версия интерфейса командной строки, и именно о ней рассказывается в большинстве обучающих материалов. Поэтому будьте внимательны при запуске CMD, язык командной строки Windows отличается от работы с PowerShell. Если использовать инструкцию для одного из интерфейсов, работая в другом, можно получить неожиданный результат.
Как открыть командную строку: все способы
Существует несколько способов, как открыть командную строку в Windows. Разберем наиболее актуальные для текущих версий операционной системы.
Запуск через окно «Выполнить»
Один из стандартных способов запуска командной строки — через окно «Выполнить», которое вызывается сочетанием клавиш Win+R. В нем нужно набрать команду для вызова командной строки Windows, она пишется как cmd. После ввода этого слова нажмите Enter или кнопку OK, командная строка запустится.
Окно «Выполнить» с введенной командой запуска
Запуск через меню Win+X
В Windows 10 есть удобное меню, позволяющее запустить основные управляющие программы с помощью простого меню. Нажмите Win+X, чтобы вызвать его. В списке у вас будет два пункта: просто «Командная строка» и «Командная строка (администратор)». В большинстве случаев вас устроит первый вариант, но иногда для действия, например для удаления некоторых файлов, требуется доступ администратора. В этом случае необходимо использовать запуск командной строки от администратора.
Меню, которое позволяет вызвать командную строку
В некоторых Windows 10 в списке, который появляется по Win+X, командная строка заменена на инструмент PowerShell. Мы уже говорили в предыдущем разделе, что это похожие инструменты, но они все же отличаются между собой. Если в вашей операционной системе по умолчанию предлагается использовать PowerShell, а вы хотите интерфейс CMD, используйте другие горячие клавиши для запуска командной строки Windows, например, Win+R.
Меню Win+R, в котором вместо командной строки предлагается запустить PowerShell
Запуск через меню «Пуск»
Ярлык запуска интерфейса командной строки можно найти в меню «Пуск». Для этого откройте его, прокрутите список программ до папки «Служебные — Windows», в этом списке найдите нужный ярлык и нажмите на него левой кнопкой мыши. Если требуется запуск от имени администратора, то нажмите правой кнопкой по ярлыку, выберите пункт «Дополнительно» и после — «Запуск от имени администратора».
Запуск командной строки через список программ в меню «Пуск»
В некоторых версиях Windows ярлык запуска интерфейса командной строки может находиться не в списке служебных программ, а в стандартных программах.
Другой вариант расположения ярлыка в меню «Пуск»
Запуск через меню «Пуск» с поиском
Для открытия программы в современных версиях Windows вовсе не обязательно просматривать все ссылки и искать нужное название. Можно просто открыть меню «Пуск» и написать cmd. После этого простого поиска справа в меню «Пуск» появится возможность запустить интерфейс командной строки с разными опциями: обычным способом или от администратора.
Запуск командной строки через поиск в меню «Пуск»
Резюмируем информацию о том, как вызвать командную строку в Windows:
- если вам требуется просто открыть интерфейс командной строки, можно использовать команду cmd в окне «Выполнить». Другие способы — через меню «Пуск» или меню Win+X простым нажатием левой кнопки на нужный пункт;
- если необходимо запустить командную строку от имени администратора, вам нужно использовать соответствующий пункт в меню Win+X, либо нажать правой кнопкой по ярлыку командной строки в меню «Пуск»;
- в некоторых случаях классическая командная строка может быть заменена на PowerShell. Это похожий, но не точно такой же интерфейс. Поэтому, если вы читаете инструкцию о классической командной строке, используйте иной способ для ее запуска.
Два варианта интерфейса командной строки: обычный и от администратора (разница в заголовке)
Базовые команды интерфейса командной строки Windows
Теперь, когда вы знаете, где вызывается командная строка Windows, стоит научиться ее использовать. Расскажем об основных командах, которые помогут использовать этот инструмент.
Ввод данных в командную строку
Командная строка выглядит как черный экран с мигающим курсором на месте текста, который вы будете вводить. Вы можете:
- вводить текст с клавиатуры на любом языке;
- вставлять скопированные команды с помощью правой кнопки мыши или сочетания Ctrl+V или Shift+Insert;
- перемещать курсор по тексту с клавиатуры стрелками, чтобы исправить опечатку;
- повторить уже введенную и вызванную команду, нажав стрелку вверх на клавиатуре, это поможет, если вы, например, опечатались в пути файла и не хотите вводить все заново;
- дополнить часть пути к файлу с помощью клавиши Tab. Для этого вам нужно начать вводить путь в консоль и нажать Tab, путь автоматически дополнится наиболее подходящим названием. Можно нажимать Tab несколько раз, чтобы изменять варианты автодополнения;
- копировать текст из командной строки с помощью сочетания клавиш Ctrl+C или (предпочтительно) выделив текст мышкой и нажав Enter.
Вы не можете:
- выделить кусок текста и стереть его;
- перемещать курсор мышью — только стрелками;
- вызвать контекстное меню, по умолчанию оно отключено.
Обратите внимание, что выделение и курсор для ввода текста в командной строке — разные, не зависящие друг от друга сущности. Их положение друг от друга не зависит.
Скриншот выделения и курсора: выделение находится на букве h и ее можно скопировать, курсор находится в конце строки, и именно там будет появляться текст, если пользователь начнет его вводить
На первый взгляд интерфейс неудобный и довольно ограниченный. Но, привыкнув, что большая часть команд вводится с клавиатуры, вы освоите его и сможете быстро использовать большинство команд.
Совет! Поэкспериментируйте с командой help: откройте командную строку, наберите слово «help» и нажмите Enter. Ознакомьтесь со списком команд и убедитесь, что можете повторно заполнить поле ввода словом «help», просто нажав стрелку вверх.
Работа с файлами — команда cd
Мы уже неоднократно говорили о том, что командная строка позволяет быстро и эффективно работать с файлами. Чтобы использовать ее для таких целей необходимо в первую очередь научиться открывать файлы и перемещаться между директориями. Для этого используется команда cd (сокращение от change directory. т.е. «сменить директорию»). Например, для того чтобы открыть папку Films на диске C необходимо написать в командной строке cd C:\Films и нажать Enter.
Скриншот перехода в папку Films на диске C с помощью интерфейса командной строки
Подобным образом можно запускать программы и открывать файлы из выбранной директории. Например, если у вас в папке Films лежит видео под названием Windows 10.mp4, вы можете ввести это название в командную строку, нажать Enter, и видео начнет проигрываться в плеере.
Скриншот запуска файла видео под названием «Windows 10.mp4» из директории «С:\Films»
Выйти из папки Films на уровень выше можно, введя команду cd ... Если вы хотите сменить диск, то нужно сначала написать в строке его букву с двоеточием, нажать Enter, а после, с помощью команды cd перемещаться по директориям.
Скриншот перехода между жесткими дисками: сначала перемещение к диску E, а после — в одну из папок на этом диске
Получение данных о директории — команда dir
Перемещаться между директориями с помощью команды cd удобно, только если вы знаете, где какая папка находится и какие файлы в ней лежат. Получить эту информацию, не выходя за пределы консоли, поможет команда dir. Введите ее, находясь в любой директории, и вы получите подробный список папок и файлов, которые в ней находятся.
Список файлов и папок, который отображается после использования команды dir
Проверка доступа к сайту — команда ping
Если у вас плохо работает интернет, можно воспользоваться командой ping, чтобы проверить, отзывается ли какой-нибудь популярный сайт. Чаще всего для проверки связи «пингуют» Яндекс. Введите команду ping ya.ru, чтобы узнать, как идут пакеты до этого ресурса. Если интернет по какой-то причине не работает, в консоли будет написано «не удалось обнаружить узел». Если же связь есть, вы получите отчет: сколько пакетов было отправлено, сколько получено и сколько времени это заняло.
Скриншот интерфейса командной строки после использования команды ping ya.ru
Удаление нескольких файлов одинакового формата — команда del и маска имени файла
Одна из удобных функций интерфейса командной строки — быстрая работа с файлами, отобранными по определенным характеристикам. Для отбора чаще всего используются маски имени файлов, например, написав * вместо части имени, вы говорите, что на этом месте может быть сколько угодно символов. Таким образом, маска *.jpg позволит выбрать все файлы формата JPEG. Если к выбору добавить команду, например, удаление (del), то можно удалить из папки все файлы формата JPEG. Команда будет выглядеть следующим образом: del *.jpg.
Скриншот удаления всех файлов формата JPEG из директории Pictures
Помощь и большой список стандартных команд — команда help
Мы описали основные параметры командной строки Windows, которые можно использовать для управления компьютером. Но команд на самом деле намного больше. Список их легко вызвать введя команду help. Используйте ее, если хотите расширить свои возможности.
Список, который появляется после вызова команды help
Внутренние и внешние команды CMD
Команды, которые мы описали выше, являются внутренними, т. е. теми, которые уже встроены в операционную систему. Также с помощью консоли можно выполнять внешние команды — те, которые пользователь создает сам либо с помощью сторонних программ. Например, если вы решите изучать Python и установите на компьютер программу VS Code, в командной строке появится дополнительная команда code, которая ее запускает.
Еще одна внешняя команда — ffmpeg. Она запускает утилиту FFmpeg, которая может конвертировать видео из одного формата в другой. Ее также необходимо устанавливать отдельно.
Другой пример внешней команды — yt-dlp. Она запускает утилиту, которая позволяет скачивать видео с YouTube и многих других видеохостингов и аудиохостингов.
Все внешние команды появляются только после корректной установки соответствующих программ на компьютер. Если софт не установлен или при установке произошла ошибка, вызов через интерфейс CMD может не работать. Вы также можете написать собственную программу и добавить в нее код для вызова через командную строку Windows.
Итак, мы рассмотрели, как открыть командную строку администратора Windows, что пользователь может делать с помощью этого интерфейса и узнали базовые команды CMD. Этого вполне достаточно, чтобы далее разобраться самостоятельно с управлением файлами и другими аспектами. Однако мы рекомендуем с осторожностью использовать любые системные инструменты, т. к. они дают большую свободу действия, нежели графический интерфейс. Прежде чем использовать команды, убедитесь, что вы понимаете, что они делают, иначе можно случайно потерять все данные, отформатировав жесткий диск.
Download Article
A quick guide to accessing the Windows command prompt (CMD)
Download Article
- Searching for Command Prompt
- Using Run
- Via the Taskbar (Windows 10)
- Via the Taskbar (Windows 11)
- Navigating to Command Prompt
- Using File Explorer
- Video
- Q&A
|
|
|
|
|
|
|
The command prompt can be used to execute specific commands and perform advanced functions. If you need to troubleshoot your Windows laptop or computer, you may need to run the command prompt. Luckily, you can launch the Command Prompt (also called CMD, Command Line, Command Line Interface, or CLI) using a variety of easy methods. You must have administrator access to run the command prompt, so you won’t be able to do this on school computers or other locked devices. This wikiHow will show you how to get to and open the command prompt (CMD) on your Windows 8, 10, or 11 computer.
Ways to Open CMD in Windows
Search for «Command Prompt» in the taskbar (or Start menu, on older versions of Windows). You can also open it via the Run dialog by pressing Win + R and typing «cmd.» On Windows 10 and 11, you can right-click the Windows icon in the taskbar to pull up PowerShell or Terminal.
-
If you don’t see the search bar or magnifying glass icon, press the Windows key or click the Start button. You can search for Command Prompt on all supported versions of Windows, such as Windows 8, Windows 10, and Windows 11.
- If you’re using Windows 8, place your mouse cursor in the top-right corner of the screen, then click the magnifying glass icon when it appears.
-
Typing into the Start menu will automatically begin a search.[1]
Advertisement
-
You should see the Command Prompt icon appear near the top of the Start window. Clicking its icon will open the Command Prompt.
- If you need to run Command Prompt as an administrator, right-click Command Prompt in the Start menu and click Run as administrator.
Advertisement
-
On your keyboard, press ⊞ Win+R at the same time. The Run window will open.[2]
- Alternatively, you can right-click the Start icon (or press ⊞ Win+X) and click Run.
-
This is the command to open Command Prompt.
-
This will run the «cmd.exe» command, which opens Command Prompt.
- You’ll now be able to use CMD.
Advertisement
-
The Power User menu appears when you right-click the Windows icon in the taskbar. This menu has a number of options, including one that says Windows PowerShell. PowerShell is similar to Command Prompt, but it’s not exactly the same. In order to get Command Prompt back in the Power User menu, follow these steps:
- Press ⊞ Win+I to open the Settings menu.
- Click Personalization, which has an icon of a brush on paper.
- Click Taskbar, which has an icon that looks like the taskbar.
- Toggle off «Replace Command Prompt with Windows PowerShell.»
- Close the Settings menu.
-
The Power User menu will appear.
-
If you need to use Command Prompt as an admin, click Command Prompt (admin) instead.
Advertisement
-
This will open the Power User menu. In Windows 11, you will see Terminal and Terminal (admin) in the Power User menu instead of Windows PowerShell and Windows PowerShell (admin).
- The Terminal option in this menu still opens Windows PowerShell, the menu name is simply different than Windows 10.
- Unlike Windows 10, you cannot change Terminal to Command Prompt in this menu like you could change Windows PowerShell to Command Prompt. However, you can still easily access Command Prompt from the Power User menu.
-
If you need to run Command Prompt as an administrator, choose the admin option.
-
Next to the tab that says Windows PowerShell, there will be a plus sign, then a dropdown arrow.
-
You can also use the shortcut Ctrl+⇧ Shift+2. This will open Command Prompt in a new tab.
Advertisement
-
If you’re on an older version of Windows, you may need to click the Start button. You can also press the ⊞ Win key.
-
This folder will be near the bottom of the Start window.[3]
- On Windows 11, click All apps, then Windows Tools.
-
It should be near the top of the Windows System folder. This will open Command Prompt.[4]
- On Windows 11, this will be at the top of the Windows Tools folder.
- If you’re unable to open the Command Prompt, you may need to open as an admin.
Advertisement
-
Open the File Explorer. You can do this by either clicking the File Explorer icon on your taskbar (which looks like a yellow file folder) or by searching for «File Explorer» in the taskbar (or Start menu) search.
-
This will be near the top of the window.[5]
- You might see Quick access in the address bar by default.
-
This will replace any text in the address bar with your new path.[6]
- The Command Prompt will open.
Advertisement
Add New Question
-
Question
How do I close out Command Prompt?
ClixTech Australia
Community Answer
Type «exit» in the Command Prompt, or press the red «X» in the top right corner, or press Alt+F4 on the keyboard. Check out the Close Command Prompt article for more detailed instructions!
-
Question
What do I do if I can’t use Microsoft Edge and the Start button?
Press the Windows Key + R, then type in cmd.exe and hit enter.
-
Question
How do I stop Windows command prompt from starting up automatically?
If it starts up every time, then something is causing it. It may be a program or a shortcut to command prompt that is saved in your Windows start folder. If you want to stop it from appearing altogether by uninstalling it, you won’t be able to.
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
-
Command Prompt is a good place to run legacy or specialty software. You might also use it if you’re trying to manipulate specific files.
Thanks for submitting a tip for review!
Advertisement
-
If you’re using a computer with restricted access to settings and programs, you may not be able to open Command Prompt.
Advertisement
About This Article
Thanks to all authors for creating a page that has been read 747,468 times.
Is this article up to date?
Last Updated :
10 Feb, 2025
The Command Prompt is a powerful tool in Windows for executing commands, troubleshooting issues, and automating tasks. Whether you’re using Windows 11, 10, 8, or 7, this guide covers all the methods to open Command Prompt quickly and efficiently.
8 Proven Methods to run the Command Prompt (cmd) in Windows Any Version
Command prompt is widely used not only to navigate, open or close a folder , it’s essential to troubleshoot windows problem as well. So lets understand top 10 methods to open Windows command line seamlessly.
Method 1: Using the Start Menu Search
- Windows 11/10/8:
- Click the Start button (Windows logo).
- Type
cmd
orCommand Prompt
. - Press Enter or click Open.
- Windows 7:
- Click the Start button.
- Go to All Programs > Accessories > Command Prompt.
Method 2: Using the Run Dialog Box
- Press
Win + R
to open the Run dialog. - Type
cmd
and press Enter.
Method 3: Using Task Manager
- Press
Ctrl + Shift + Esc
to open Task Manager. - Go to File > Run New Task.
- Type
cmd
and click OK.
Method 4: Using File Explorer
- Open File Explorer (
Win + E
). - Type
cmd
in the address bar and press Enter.
Method 5: Using Power User Menu (Windows 11/10/8)
- Press
Win + X
to open the Power User Menu. - Select Command Prompt or Command Prompt (Admin).
Method 6: Using Search Bar (Windows 11/10)
- Click the Search icon (magnifying glass) or press
Win + S
. - Type
cmd
and press Enter.
Method 7: Using Desktop Shortcut
- Create a Shortcut:
- Right-click on the desktop.
- Select New > Shortcut.
- Type
cmd.exe
and click Next. - Name the shortcut (e.g., Command Prompt) and click Finish.
- Double-click the shortcut to open Command Prompt.
Method 8: Using Command Prompt in Safe Mode
- Restart your PC and press
F8
(Windows 7) orShift + F8
(Windows 10/11) during boot. - Select Safe Mode with Command Prompt.
Access Command Prompt as Administrator — 2 Easy Steps
Commands like ip.config, scf, powercfg, chkdsk etc. requires Administrator Permission to succesfully run in Command Prompt. In such cases you need to run Command Prompt on an Administrative mode to get the privilege to run those command line prompt, follow the below steps:
Step 1: Open CMD and select ‘Run as Admin’
Type cmd in search bar. Right-Click on Command Prompt and select Run as administrator option or Use the Power User Menu (Win + X
) and select Command Prompt (Admin).
Step 2: Enter Admin Username and Password
Also, you will see a pop up window of » User Account Control » to allow this app make changes in your device, To continue, enter an admin username and password. Click Yes to proceed.
Note: You will notice Administrator : command Prompt written in Cmd window, indicating that you are using cmd as an Administrator.
Effective Use of Command Prompt
You can run some of the basic commands to test the command prompt:
- To check the IP address: ipconfig
- To test the Internet Connection: ping google.com
- To check for Disk Errors: chkdsk
- To scan and repair any system files: sfc /scannow
Common Error & Fixes While Opening of Command Prompt
There are certain issues and errors that might occur while trying to access the command prompt, here are some of the most common error that might occur and how to get rid of them:
1. CMD Not Opening
- Open the task manager and navigate to File > Run New Task > type «cmd» and hit the enter button.
- Alternatively, you can open the Windows PowerShell as admin and run the SFC Scan following this command: sfc /scannow
- Check for malware using Windows Defender or Malwarebye
2. Access Denied
You can try these methods if you’re unable to open CMD as an admin
- Make a right-click on the Command Prompt > Run as administrator
- Enable the hidden admin account using:
- net user administrator /active:yes
3. CMD Closes Immediately
- Restart your PC in the Safe Mode (Shift + Restart > Troubleshoot > Advanced options > CMD
- Scan for Malware
- If you’re using a batch file, add @echo off and pause before running
4. «Not Recognized as a Command» Error
Open System Properties using sysdm.cpl > Environment Variables > Find path > Click Edit > Add
C:\Windows\System32
5. «System Cannot Find the Path Specified»
Check if the folder exists by running:
cd C:\Users\THIS PC\Documents
Reset Path Variables in Environment Variables.
6. CMD Opens in the Wrong Directory
Make a right click on the CMD > Properties > Change Start In: to %GFGPROFILE%
These simple steps will fix most Command Prompt issues in Windows 11, 10, 8, and 7.
Conclusion
By following these fixes, you can resolve most Command Prompt errors and ensure smooth access in Windows 11, 10, 8, and 7. Whether it’s cmd not opening, access denied, closing instantly, or showing errors, these solutions will help you troubleshoot efficiently.
Still facing issues? Try creating a new user profile or resetting Windows settings as a last resort.