Очистить историю командной строки windows

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

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

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

Сначала о возможностях работы с историей команд в командной строке Windows, они отличаются от таковых для PowerShell.

Выбор команды из истории в командной строке

Прежде чем начать, отмечу: история команд сохраняется только для текущей сессии, если вы закроете окно, история будет автоматически очищена.

Теперь по порядку о возможностях работы с историей в командной строке, большая часть доступна с помощью клавиш:

  • Стрелки «Вверх» и «Вниз» на клавиатуре позволяют быстро «листать» предыдущие и следующие введённые команды, автоматически вставляя их в поле текущего ввода.
  • Page Up — ввести первую команду, использованную в текущей сессии.
  • Page Down — ввести последнюю команду текущей сессии.
  • F1 — ввод предыдущей использованной команды по одному символу.
  • F2 — копирование текста предыдущей команды до символа (не включая его), который вы введёте.
    Ввод символа, до которого нужно скопировать команду

  • F3 — копирование части предыдущей команды в текущую начиная с символа, на котором вы находитесь в текущей строке. Например, ранее вы использовали команду ping -4 remontka.pro Если далее ввести ping -6 и нажать F3, команда будет дополнена до ping -6 remontka.pro
  • F7 — просмотр истории команд в виде списка во всплывающем окне с возможностью выбора стрелками. Для закрытия окна нажмите клавишу Esc.
  • F8 — поиск команды в истории, текст которой совпадает с текущим вводом. Например, если вы ранее использовали команды chkdsk C: /f то можно ввести c и нажать F8 Повторные нажатия этой клавиши позволяют листать найденные команды, содержащие введённый текст.
  • F9 — поиск команды в истории по её номеру в списке.
  • Команда doskey /history показывает все использованные в текущей сессии команды прямо в командной строке.
    Просмотр истории команд в командной строке

  • Для сохранения истории команд в файл, используйте команду
    doskey /history > путь_к_файлу.txt
  • Alt+F7 — очистить историю в текущей сессии, не закрывая командной строки, можно нажать клавиши
  • Команда doskey /listsize=0 отключит хранение истории команд в текущей сессии.
  • Для очистки окна консоли от ранее вводившихся команд можно использовать команду cls

Windows PowerShell

Некоторые действия с историей в окне Windows PowerShell совпадают с таковыми для командной строки, другие — отличаются. Доступные возможности по порядку:

Очистка истории в диалоговом окне «Выполнить»

Некоторые пользователи могут искать в Интернете как очистить историю командной строки Windows, имея в виду не командную строку, а диалоговое окно «Выполнить» (Win+R), история в котором отображается в списке. Если вы такой пользователь, решение следующее:

  1. Запустите редактор реестра, используя Win+Rregedit
  2. Перейдите к разделу реестра
    HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\RunMRU
  3. Удалите ненужные значения (можно удалить все, оставив лишь одно «По умолчанию».
    Очистка истории диалогового окна Выполнить

В результате история будет очищена.

Clearing the command history in PowerShell and Command Prompt is essential for improving readability, avoiding confusion, and maintaining privacy. Sometimes, we need to declutter the command window screen and start fresh. In this article, we’ll show you how to clear the command history screen in PowerShell and Command Prompt in Windows 10 and 11.

Before we learn the methods to clear the command screen in PowerShell, let’s check out the basics of command history. PowerShell keeps track of commands entered into the shell. This history of commands can be viewed and accessed in several ways.

  1. Up and down arrow keys: Pressing the up arrow key will cycle through your previously entered commands, allowing you to quickly access and reuse them.
  2. Get-History cmdlet: The Get-History cmdlet allows you to view a list of all the PowerShell commands used during your current session. This can be useful if you have to refer back to a specific command or if you want to see a list of all the commands you have entered so far.
  3. Invoke-History cmdlet: The Invoke-History cmdlet allows you to rerun a specific command from your command history without typing it out again. Using the ID number associated with the command in your history list will rerun the command with an ID of 23 from your history list.
    Example: Invoke-History -ID 23

Clearing the Command Screen in PowerShell

It is easy to clear the commands and their outputs in the current PowerShell session using PowerShell cmdlets (their aliases) and keyboard shortcuts.

Clear PowerShell Screen

Type the following cmdlet in PowerShell and hit Enter.

Clear-Host

clear host cmdlet in powershell window

This will clear the command window screen as shown below.

powershell command window screen cleared

Alternatively, you can use the aliases of the Clear-Host cmdlet to clear the PowerShell console. Simply type “cls“, “cls /?” or “clear” and hit Enter in the PowerShell window. This will remove all previous commands and outputs from the screen so that you start afresh with new tasks.

Moreover, you can also use keyboard shortcuts to clear the PowerShell screen in Windows 10 and 11. Pressing “Ctrl + L” on your keyboard will have the same effect as executing Clear-Host.

Clear PowerShell Command History

While Clear-Host clears the current console, the Clear-History cmdlet and Alt+F7 are used to clear the command history in PowerShell. If the PowerShell’s Clear-History is not working for you and it doesn’t clear the command history, it’s because PowerShell’s history is saved in a text file named ‘ConsoleHost_history.txt‘ at the following location.

C:\Users\user\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\

Use the following command to get the location of the command history text file in Windows 10 and 11.

(Get-PSReadlineOption).HistorySavePath

powershell command history text file location

You can either navigate to the above location on your PC and remove the contents of the ‘ConsoleHost_history.txt’ file, or execute the following command to clear the command history in PowerShell.

[Microsoft.PowerShell.PSConsoleReadLine]::ClearHistory()

You can also instruct PowerShell not to save the command history in the ‘ConsoleHost_history.txt’ at all.

Set-PSReadLineOption -HistorySaveStyle SaveNothing

To enable the saving of command history to the text file, use this command:

Set-PSReadLineOption -HistorySaveStyle SaveIncrementally

Clearing the CMD Screen and Command History

Clear Command Prompt Screen

You can clear a single line or everything from the Command Prompt screen and start with a clean slate.

To clear the Command Prompt screen on your Windows 10/11 PC, type cls or CLS in the command window, and press Enter.

use cls command to clear command prompt screen

Here are a few shortcut keys to help you while using the Command Prompt:

  • Esc or Escape: If you type a wrong command by mistake, you can quickly clear the line from the CMD window screen by pressing the Esc key.
  • Ctrl + Backspace: Deletes one left of the cursor.
  • Ctrl + C: Leave the line you are typing or terminate the command in process and start with a new prompt.
  • Alt+F4: Close an open PowerShell or Command Prompt window.

Clear the Command Prompt History

Command history is a useful feature in the Command Prompt. It allows you to access your past commands quickly and reuse them when needed. You can view the commands used in the current session in two ways:

  • Up and down arrow keys: Cycle through your previously entered commands.
  • F7: Shows the list of commands used in the CMD. You can use the up and down arrow keys to highlight the commands and press Enter to use them.
    use f7 to view command prompt history

If you want to clear the Command prompt history on Windows 10/11, press Alt+F7. That’s it! The command history will be cleared.

Using the “cls” command in Command Prompt and the “Clear-Host” cmdlet in PowerShell are simple ways to clear your screen and declutter your workspace. With these tips, you can effectively use clear screen commands and improve your productivity while working with PowerShell and Command Prompt.

Read Next: 3 Ways to Replace PowerShell with Command Prompt

Was this Article helpful?

YesNo

  • Home
  • News
  • [SOLVED] How to Clear Command Prompt Screen Windows 10

By Alisa |
Last Updated

This post provides quick ways to clear Command Prompt (cmd.exe) screen in Windows 10. For troubleshooting Windows problems, MiniTool software also provides some free tools like free data recovery software, hard drive partition manager, PC backup software, etc.

Windows Command Prompt (cmd.exe) lets us quickly open applications, execute tasks, troubleshoot some Windows issues, etc. by typing command lines. After you type many command lines and finish the tasks, or type wrong command lines, how to clear Windows Command Prompt screen in Windows 10?

Check the easy ways below for how to clear CMD screen in Windows 10.

Clear Command Prompt Screen with CLS Command

After you open Command Prompt in Windows 10, and enter multiple command lines in the screen, you can type cls command line in Command Prompt window, and hit Enter button. This will clear the CMD screen in Windows 10. All typed previous commands in Command Prompt window will be cleared.

Close Command Prompt and Open It Again to Clear Screen

You can also close Command Prompt window and open again, it will also clear the Command Prompt screen in Windows 10.

Clear Command Prompt Screen with Keyboard Shortcut?

If the Command Prompt window is cluttered and you want to clear the screen, you may wonder if there is a keyboard shortcut to easily clear it. Some online posts suggest using Alt + F7 keyboard shortcut to clear the command history. But I tried this way, it doesn’t work.

How to View Command Prompt Command History

After you type a series of command lines in Command Prompt window, you can type doskey /history command line, and hit Enter. This command will display all the commands you typed in the same sequence as you entered.

To view all command lines you entered in Command Prompt window after you access CMD, you can also press F7 key. This will pop up a window with a list of all previous typed command lines. You can use the Up and Down arrow key to select any command line in the list and press Enter to locate it.

How to Save Command Prompt History

You can enter this command line doskey /HISTORY > filename.txt to save the commands history to a TXT, HTML, CSV, RTF file. You can enter a file name and a file extension. The file will be saved to the location where you execute this command.

What You Can Do with Command Prompt

You can use Windows Command Prompt to do many things. Below we introduces three common usages of Command Prompt. Press Windows + R, type cmd, and hit Enter to open Command Prompt.

open Command Prompt

Organize Your Hard Drive Partitions

You can run Windows Diskpart utility in Command Prompt to manage computer hard drive partitions.

You can type diskpart in Command Prompt window to open Windows Diskpart tool. Below is how to partition external hard drive with Diskpart.

  • list disk
  • select disk * (select the external hard disk)
  • create partition primary size=* (specify a partition size in MB)
  • assign letter=* (set a drive letter for the new partition)
  • format fs=ntfs quick
  • exit

use Command Prompt to manage partitions

Check and Repair Disk Errors

You can also type chkdsk *: /f /r command in Command Prompt, and hit Enter to use Windows CHKDSK to check and repair hard disk errors. Replace “*” with the target partition drive letter.

CHKDSK command

Detect and Repair Corrupt System Files

If your computer has problems, you can use Windows SFC tool to check and repair corrupted system files. You can type sfc /scannow command in Command Prompt, and hit Enter to use SFC tool to find and repair corrupted/missing system files.

Verdict

In conclusion, the easiest way to clear Command Prompt screen is to use CLS command or restart Command Prompt application.

About The Author

Position: Columnist

Alisa is a professional English editor with 4-year experience. She loves writing and focuses on sharing detailed solutions and thoughts for computer problems, data recovery & backup, digital gadgets, tech news, etc. Through her articles, users can always easily get related problems solved and find what they want. In spare time, she likes basketball, badminton, tennis, cycling, running, and singing. She is very funny and energetic in life, and always brings friends lots of laughs.

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

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.

Download Windows Speedup Tool to fix errors and make PC run faster

This post will explain how to clear the Run dialog command history in Windows 11/10. The Run dialog box is a very powerful tool in Windows. You can use this utility to open your desired apps and documents directly whose path is known. All you need to type the app name or the folder path in the text box and then press Enter, it will take you to the preferred location.

Besides this, it stores the command you use to open the application on your computer. And when you type the first letter of any command, all the matching commands get listed there. If you want to remove the items in your Run dialog history then this post will help you do so.

How to clear Run command history in Windows 10

Make sure to back up the Windows Registry because modifying the registry is risky if you don’t know what you are doing. To disable Run command history you need to clear Most Recently Used (MRU) lists.

On Windows 11/10, you can use the Registry Editor if you have signed into your computer as an administrator.

  1. Search for regedit in the Windows search box.
  2. Select the Registry Editor from the search result.
  3. If a UAC popup appears on the screen, click on the Yes button to give your approval.
  4. Navigate to the path – \Explorer\RunMRU
  5. Right-click on the registry value and select the Delete option.
  6. Click the Yes button to confirm the value delete.
  7. This way you can delete all the commands you want to remove from the Run dialog history.

If you want to learn more about these steps in detail, continue reading:

How to clear Run dialog history in Windows 10

To get it started, you need to open Registry Editor on your computer first. To do this, you can search for “regedit” in the Taskbar search box and click on the Registry Editor in the search result.

When the UAC prompt appears on the screen, click on the Yes button to open the Registry Editor on your computer.

After opening the Registry Editor, navigate to the following path:

HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\RunMRU

On the resulting key, you will find a list of DWORD values named a, b, c, d, and so on.

Now go through the list and delete all the values except the Default key to clear the Run dialog history on your PC.

If a popup arrives on the screen for your approval, simply click the Yes button.

If the Registry key does not exist, you may have to create it.

There are two additional steps you may have to take:

  • Open Windows Settings > Personalization > Start. Turn off and then again Turn on the Show recently opened items in Start, Jump Lists and File Explorer setting.
  • Open Internet Options and click on the Delete Browsing History button. Next, select History, Download history and Form data, and done, click Delete.

While most junk file cleaners like CCleaner, do clear the MRU lists, you can also use dedicated freeware like MRU Blaster, to clear Most Recently Used (MRU) lists and delete all the traces and usage tracks from the nook and corner of your Windows, including Explorer, Office, Visual Studio, etc. It can find and remove over 30,000 MRU lists. Anti Tracks, Wipe Privacy Cleaner, and Privacy Eraser are other tools in this category that can help you clean Most Recently Used Lists in Windows.

Also read: How to view, save and clear Command Prompt command History in Windows.

Digvijay is a Windows enthusiast who likes to write about the Windows OS and software in specific, and technology in general. When he is not working, he would either surf the web or dives into learning tech skills.

Reader Interactions

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как загрузиться в безопасном режиме windows server 2012
  • Touch screen for windows 10
  • Проводник windows показать скрытые файлы
  • Снимок экрана в windows 10 ножницы
  • Драйвер для расширения экрана windows 10