Как посмотреть историю команд cmd windows

Работая в классической командной строке или PowerShell, вы в любой момент можете нажать F7 и просмотреть историю всех выполненных команд. И не только просмотреть, но и выбрать любую из них. Это очень удобная и полезная функция, которая позволяет экономить время при повторном наборе команд, но пользоваться ее преимуществами получится только в текущем сеансе.

Вывод истории команд клавишей F7

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

Командная строка

Для получения списка выполненных команд помимо клавиши F7 можно использовать специальную команду doskey с ключом history. История выводится непосредственно в консоль и также доступна только в текущей сессии, поэтому для ее сохранения используем обычное перенаправление в файл, например, вот так, дешево и сердито:

doskey /history > C:/20.05.20.log

Результат выполнения команды doskey /history

Сохраненная в файле история команд

Формат файла истории не обязательно должен быть LOG, уместны также форматы TХT, HTML, CSV и даже RTF.

В случае с консолью PowerShell всё куда интереснее. Начиная с пятой версии консоль сохраняет все введенные и выполненные командлеты в текстовый лог ConsoleHost_history.tхt, расположенный по пути %userprofile%/AppData/Roaming/Microsoft/Windows/PowerShell/PSReadline.

Файл ConsoleHost_history

Даже если вы завершите сессию в консоли и выключите компьютер, команды останутся сохраненными и будут доступны для вызова в PowerShell нажатием клавиши «Стрелка вверх». Каждое нажатие выводит предыдущую команду, но можно отобразить и весь список выполненных команд сразу. Делается это так:

cat (Get-PSReadlineOption).HistorySavePath

Вывод истории команд в консоли PowerShell

Отвечающий за историю модуль поддерживает и другие функции. Если вы введете команду Get-PSReadlineOption, то получите в консоли приличный список доступных параметров. Ознакомиться с их назначением можно в официальной документации к PowerShell, но смысл некоторых из них понятен и так. К примеру, нетрудно догадаться, что ключ MaximumHistoryCount устанавливает максимальное число элементов, сохраняемых в список истории.

Параметры сохранения истории

Команда Remove-Item (Get-PSReadlineOption).HistorySavePath очищает историю введенных команд, Set-PSReadlineOption -HistorySaveStyle SaveNothing запрещает ведение истории, Set-PSReadlineOption -HistorySaveStyle SaveIncrementally вновь разрешает сохранение данных.

Управление историей команд

В целом, начинающему администратору вполне должно хватить данного функционала для облегчения работы в консоли. Если же вдруг при выполнении любой из приведенных выше команд появится ошибка «имя командлета не распознано», это с большой долей вероятности укажет на отсутствие требуемого модуля. Установить его в Windows 10 с PowerShell v5 можно командой Install-Module PSReadLine с последующим разрешением на подключение поставщика NuGet.

Установка модуля в PowerShell

Андрей Хамлюк

Эксперт по ремонту и настройке ПК с более чем 5-летним опытом работы. Имеет профильное образование по специальности оператор ЭВМ.

Задать вопрос

Командная строка – это не что иное, как черно-белая утилита командной строки, которая поставляется из коробки в Windows 10/8/7. Но те, кто знает его истинный потенциал, это отличная замена для стороннего программного обеспечения многих пользователей. Например, он может помочь вам организовать разделы жесткого диска, создать загрузочный USB-накопитель, обновить все файлы BIOS и многое другое. Многие администраторы и опытные пользователи, как правило, используют несколько команд в этой командной строке для выполнения своей работы. Сегодня мы поговорим о 2 методах, которые помогут пользователю просматривать историю своих командных строк, и об одном способе сохранения этой истории в Windows 10.

Содержание

  1. Просмотр, сохранение, очистка истории команд командной строки
  2. 1] Просмотр истории команд с помощью DOSKEY
  3. 2] Просмотр истории CMD с помощью клавиши F7
  4. 2] Сохранить историю командной строки
  5. 4] Очистить историю командной строки, используя Alt + F7

Просмотр, сохранение, очистка истории команд командной строки

Мы рассмотрим следующие темы:

  1. Просмотр с использованием DOSKEY.
  2. Просмотр с помощью клавиши F7.
  3. Сохраните историю командной строки.
  4. Очистить историю командной строки.

1] Просмотр истории команд с помощью DOSKEY

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

 doskey/history 

После этого вы сможете проверить все команды, которые вы только что ввели во время этого сеанса, в командной строке в той же последовательности, в которой вы их вводили.

Вы можете проверить фрагмент экрана того же самого выше.

2] Просмотр истории CMD с помощью клавиши F7

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

Чтобы просмотреть историю команд, вам нужно нажать клавишу F7 . F7 работает также для командной строки и PowerShell.

Это приведет к появлению небольшого всплывающего окна со списком всех ранее выполненных команд в сеансе.

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

2] Сохранить историю командной строки

Иногда вам может потребоваться сохранить записи команд, которые они использовали в сеансе с использованием командной строки, в файле TXT, HTML, CSV или RTF.

Для этого вы можете использовать расширение команды DOSKEY.

Вам просто нужно ввести следующую команду, а затем нажать клавишу Ввод ,

 doskey/HISTORY> SampleHistory.txt 

Затем сохраненный файл истории будет сохранен в том месте, где вы выполнили команду в окне командной строки.

4] Очистить историю командной строки, используя Alt + F7

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

Чтобы очистить историю команд, вы также можете использовать сочетание клавиш Alt + F7 . Alt + F7 работает также для командной строки и PowerShell.

Вы также можете удалить историю команд с помощью редактора реестра. Перейдите к следующей клавише:

HKEY_CURRENT_USER \ Software \ Microsoft \ Windows \ CurrentVersion \ Explorer \ RunMRU

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

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

  • Home
  • Partition Magic
  • How to View CMD History in Command Prompt/PowerShell [Full Guide]

By Ariel | Follow |
Last Updated

Sometimes you may need to view the CMD history on Windows 10/11. How to list the history of Command Prompt? If you are trying to figure it out, this post of

MiniTool

 is what you need. It provides detailed steps to get Windows CMD history in Command Prompt and PowerShell.

Command Prompt (CMD) is a widely popular and practical Windows command-line tool that can be used to deal with various works, such as CMD rename file, CMD ping test, CMD list filesCMD copy filesCMD list drivesCMD check WiFi password, and more.

However, a great many users and even professionals are unclear about these commands. For example, some users want to check the Command Prompt history in Windows 10/11 but don’t know how to do that. So, here we provide a full guide to list the CMD history in Command Prompt and PowerShell.

Can I View CMD History after Close

Unfortunately, you can only view the CMD history for current version. This is because the CMD history is not stored anywhere on Windows.

How to View CMD History in Command Prompt

How to check Command Prompt history Windows 10/11 in Command Prompt? There are 2 methods to view CMD history for currwent version. You can use the keyboard or the Doskey.

# 1. Check Windows CMD History Using the Keyboard

The first and simplest method is to use your keyboard with the Command Prompt. To do this work, follow the steps below:

Step 1. Press Win + R keys to open the Run dialog box, and then type cmd in it and hit Enter.

type cmd in the Run box

Step 2. In the Command Prompt window, press and hold the F7 key to view the history of Command Prompt. Then it will open the list of commands you currently typed in.

check CMD history using F7

Step 3. With the command history Windows opened, you can run the command again using the up or down arrow keys. Also, you can press the Esc key to exit the Command Prompt window without running any command.

Tips:

You can press Alt + F7 key to wipe the Windows Command Prompt history from the current session.

# 2. Check Windows CMD History Using the Doskey

The Doskey is another simple tool that can list the previously entered commands, edit command lines, and create macros. Here’s how to view Windows Command Prompt history using the Doskey.exe.

Step 1. Open the Command Prompt window again as we explained above.

Step 2. Type the following command and hit Enter. Then the command lines you recently executed will appear in the Command Prompt window.

doskey /history

Step 3. If you want to select and run the command, you can use the Up or Down arrow key and hit Enter. In addition, you can press the Page Down key to reenter the last command from the current session history or Page Up key to reenter the first command.

check CMD history using Doskey

Note:

Windows will automatically clear the history of CMD logs and restart it for the new session once you restart your computer.

Step 4. If there are some useful commands that you may want to save for future use, you can run the following command to export the CMD history to a txt file. You can find the txt file in your WIndows Users folder.

doskey /HISTORY > history.txt

How to View CMD History in PowerShell

PowerShell can help you find the command history on Windows 10/11 as well. It’s very simple to view the PowerShell command history. Right click the Start menu from the bottom left screen and select Windows PowerShell. In the pop-up window, type the history command and hit Enter.

PowerShell check command history

In addition, you can press Win + R keys to open the Run box, and then copy and paste the following command in it and hit Enter. It will direct you to a txt file that stores the command history of all sessions in PowerShell.

%userprofile%AppDataRoamingMicrosoftWindowsPowerShellPSReadline

check the txt file of the CMD history

Further reading: If you enter some issues like file system corruption and low disk space on Windows 10/11, don’t worry. MiniTool Partition Wizard can help you fix them easily by checking file system errors, extending/resizing partitions, analyzing disk space, upgrading to a larger hard disk, etc.

About The Author

Ariel

Position: Columnist

Ariel has been working as a highly professional computer-relevant technology editor at MiniTool for many years. She has a strong passion for researching all knowledge related to the computer’s disk, partition, and Windows OS. Up till now, she has finished thousands of articles covering a broad range of topics and helped lots of users fix various problems. She focuses on the fields of disk management, OS backup, and PDF editing and provides her readers with insightful and informative content.

Command Prompt (cmd) is a widely used command-line tool for Windows. One of the shortcomings of CMD is that it only shows the history of commands you recently executed in the current session.

If you close the current window, all history is gone. There are multiple ways to quickly access the history of commands, clear the command history, and save your command history for future reference.

We will discuss these scenarios in this article. Please note that the commands mentioned in this article work on all versions of Windows, including Windows 7, Windows 8.1, Windows 10, and Windows 11.

Table of contents

  • View Command History in Command Prompt using Doskey
  • View Command History in Command Prompt using Keyboard Shortcut
    • Search for Commands in the Command History
    • Execute Commands from CMD History
    • How to save Command Prompt History
    • How to Clear CMD History
  • View Command History in Command Prompt using Clink
  • View Command History in PowerShell and Terminal
  • Conclusion

View Command History in Command Prompt using Doskey

To view your command history in Command Prompt, simply type the following command in your CMD window.

doskey /history

All the previously executed commands you typed in the current session will be listed on the cmd screen.

doskey commands history

Doskey commands history

View Command History in Command Prompt using Keyboard Shortcut

You will only see the history for the current session in the Command Prompt window. Upon closing the Command Prompt window, all previous commands will be lost after restarting the program.

Once you have opened the Command Prompt window and started executing commands, Windows will save the history for your active session.

To see the list of recently executed commands in CMD, press the F7 key. This will open a pop-up inside CMD showing the list of recently executed commands. You can select any command and press enter and that specific command will be executed again.

View command prompt history using F7 key

View Command Prompt command history using F7

Select the command and press the Enter button. And here you are. Your command has been executed.

How To Check Command History in Command Prompt In Windows 1

Execute the command

Search for Commands in the Command History

You can also search for a specific command from your CMD history. To search for a specific command from the history, just press the F8 key, type whatever you remember, and then press the F8 key to cycle through the possibilities from the history.

For example, if the command I’m searching for starts with “ip“, I will type ip and then press the F8 key. Pressing the F8 key again will bring another possible result from history if any. Keep pressing the F8 key again and again until the history list ends.

Execute Commands from CMD History

When we pressed the F7 key, you should have noticed that each command starts with a number. If you want to use the command again and again, you can call it by its number by using the F9 key.

For example, if the command number 3 is the one I have to run, again and again, I will press the F9 key, type 3, and then press Enter. This will execute command no. 3 from the command history.

doskey /history

How To Check Command History in Command Prompt In Windows 2

Execute Command Prompt history command using doskey

Use the Up and Down arrow keys to select the command. Or you can also Copy and Paste the commands from the history that has appeared on your screen, within the CMD window.

How to save Command Prompt History

You can only view the history of commands as long as your CMD window stays open. When you close it, all commands will be gone with no mark of history. What if you need the same commands for the next use of CMD window, but you do not know which commands you executed before?

You can save your commands list as a TXT, HTML, CSV or RTF file before closing the window so that you can have a backup of your entered commands.

Type the following command to save the command history in Command Prompt:

doskey /HISTORY > history.txt

How To Check Command History in Command Prompt In Windows 3

Save Command Prompt history to file

Your file will be saved in the Users folder. Now go to the user folder and see if that has the file saved there or not.

How To Check Command History in Command Prompt In Windows 4

Command Prompt history saved to text file

Please check the history of all commands and save them in a notepad file to use any of your commands anytime you need.

You can also automatically save the commands you typed in the file when you exit Command Prompt.

To do so, run the following macro:

doskey exit=(echo/ ^& echo **** %date% %time% ****) $g$g %USERPROFILE%\commands.log ^& doskey /history $g$g %USERPROFILE%\commands.log ^& ECHO Command history saved, exiting ^& exit $*

This remaps the EXIT command to copy the command line history into your user profile folder (C:\Users\yourname\commands.log in the above example). I’ve taken this solution from serverfault. There are many other solutions for persistent history given on the page. You can check it out here.

How to Clear CMD History

Since the command history in CMD and PowerShell is not persistent, history can be cleared by closing the current CMD window. If you do not want to close the CMD window, you can also use the Alt + F7 key. This will clear the CMD history from your current session.

View Command History in Command Prompt using Clink

Clink is software that merges with the existing Command Prompt on your Windows PC. It adds extra command line features like rich command completion, cmdlet history browsing and execution, and line-editing capabilities.

These features are added by combining the existing cmd.exe file with GNU Readline libraries.

Note: Currently, Clink only works on Windows 10 and below.

Here is a complete list of the command line features which you will get in Command Prompt after installing Clink:

  • The same line editing as Bash (from GNU’s Readline library).
  • History persistence between sessions.
  • Context-sensitive completion;
    • Executables (and aliases).
    • Directory commands.
    • Environment variables
    • Third-party tools; Git, Mercurial, SVN, Go, and P4.
  • New keyboard shortcuts;
    • Paste from the clipboard (Ctrl-V).
    • Incremental history search (Ctrl-R/Ctrl-S).
    • Powerful completion (TAB).
    • Undo (Ctrl-Z).
    • Automatic “cd ..” (Ctrl-Alt-U).
    • Environment variable expansion (Ctrl-Alt-E).
    • (press Alt-H for many more…)
  • Scriptable completion with Lua.
  • Coloured and scriptable prompt.
  • Auto-answering of the “Terminate batch job?” prompt.

Let us now show you how to use Clink to view command history in Command Prompt:

  1. Download and install Clink with default settings.

  2. Run the Command Prompt.

  3. Press CTRL + R shortcut keys to enter reverse search mode.

    Enter reverse incremental search mode with Clink

    Enter reverse incremental search mode with Clink
  4. Enter the keywords for the command to search.

    Search command by keyword

    Search command by keyword

    The command will then appear after the colon.

  5. When the correct command appears, press Enter to run it.

    Run command from Command Prompt history using Clink

    Run command from Command Prompt history using Clink

Clink stores command history between sessions. This means that even if you close the window, you can search for the previously-run cmdlets in a new Command Prompt instance using the CTRL + R shortcut keys.

If you want to get rid of these extra features, all you must do is delete Clink from your PC from the Programs and Features Control Panel applet.

Uninstall Clink

Uninstall Clink

View Command History in PowerShell and Terminal

PowerShell can also be used in place of the Command Prompt. PowerShell can run all the commands for CMD plus many more. If you want to view the history of your commands in PowerShell, you have to type the history command. This will show a list of all recently typed commands inside the current PowerShell session.

I hope you have a clear understanding of how to view your history in CMD and how to save that history. If you have any questions, comment below to ask.

Conclusion

Although Microsoft has introduced a new command line tool in Windows, Command Prompt is still popular among users. Windows 11 comes with Terminal, a console program that integrates Command Prompt and PowerShell into the same program.

The new terminal has many features of the Linux command line, including the persistent command history. That’s a step in a positive direction. While it will take time to upgrade to the new programs, DOS should not be left alone until everyone is upgraded.

Главная » Программное обеспечение

На чтение 3 мин. Просмотров 1.2k. Опубликовано

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

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

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

Как скачать видео с YouTube [Учебник]

Содержание

  1. Использование меню истории команд:
  2. Использование команды Doskey History:
  3. Как сохранить историю команд в .txt файле:

Использование меню истории команд:

  1. Откройте меню «Пуск» и введите cmd в строке поиска. Нажмите на приложение командной строки, чтобы продолжить.
  2. На главном экране командной строки нажмите клавишу F7, чтобы получить доступ к меню, в котором все ранее выполненные команды перечислены в хронологическом порядке.
  3. Например, если вы выполнили команду автоотключения, как указано ниже, и хотите отключить ее, не вводя снова ту же команду.
  4. Просто нажмите F7, чтобы открыть историю команд, и используйте клавиши со стрелками вверх и вниз для перемещения между командами, которые вы хотите использовать. Нажмите Enter, когда вы выбрали нужную команду.
  5. Это выполнит выбранную команду в командной строке. Вы также можете переключаться между предыдущими командами, просто нажимая кнопки со стрелками вверх и вниз.

Использование команды Doskey History:

  1. На главном экране командной строки введите команду doskey/history и нажмите Enter.
  2. Это выведет список всех ранее выполненных команд в этом сеансе в командной строке.

Как сохранить историю команд в .txt файле:

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

  1. Откройте меню «Пуск» и введите cmd в строке поиска. Щелкните правой кнопкой мыши приложение командной строки и выберите «Запуск от имени администратора», чтобы продолжить.
  2. Введите команду doskey/h> c: \ cmd_history.txt и нажмите Enter. Это запишет историю ваших команд из командной строки в файл .txt на вашем диске C :.
  3. Нажмите клавишу Windows + E, чтобы открыть проводник. Выберите Локальный диск C: для продолжения.
  4. Файл будет представлен в виде текстового документа с именем cmd_history. Нажмите на него, чтобы открыть файл.
  5. Теперь вы можете просмотреть историю всех ранее выполненных вами команд, зарегистрированных в этом файле.

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

  • Как посмотреть загруженность оперативной памяти на windows 10
  • Как посмотреть загруженность компьютера windows 10
  • Как посмотреть загруженность жесткого диска windows 10
  • Как посмотреть заряд мышки windows
  • Как посмотреть загруженность видеокарты на windows 10