Skip to main content
Powershell

Previous Command History in PowerShell Console

By June 9, 2021January 16th, 2022No Comments

By default Windows PowerShell (as well as the command prompt) saves the history of executed commands only in the current session. When you close the PowerShell console window or restart your computer, the history of the PowerShell commands that you typed is not saved anywhere. Compared with the bash, this is a significant drawback. Starting with PowerShell 5.0 introduced in Windows 10 (Windows Server 2016), all commands entered in the PS console are now saved to a plain text log file by default.

Command History in PowerShell 5.0 and Newer

Suppose you typed and executed some complex PowerShell command. In Windows 10 and Windows Server 2016, even after restarting the computer, you can open a new PowerShell session and press the up arrow key. The last command you entered should be displayed on the screen. If you continue to press the “up” key, you will see all the commands executed earlier. Thus, using the keys “Up arrow” and “Down arrow” you can scroll through the history of PoSh commands and re-execute previously typed commands. In earlier versions of PowerShell, the history of the commands in the current session is not being saved after it is closed. Using the up/down keys, you can scroll through the command history of the current PS session only or list the entire command history using the Get-History cmdlet.

You can display more detailed information about previously executed commands in the current PowerShell session, including the command status and start/end/duration time:

Get-History | Format-List -Property *

powershell get-history

By default, the PowerShell in Windows 10 saves the last 4096 commands that are stored in a plain text file located in the profile of each user %userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt.

The history is stored separately for PowerShell and PowerShell ISE.

\ConsoleHost_history.txt - powershell commands history

If a PowerShell command takes a long time to execute, you will only see it in the command history when it completes. In cmd.exe, you can display the command history in the current session with:

doskey /history

The F7 key is used to search through cmd history.

cmd list commands - doskey /history

How to Search PowerShell Command History?

If you don’t want to scroll through the entire PowerShell command history using up/down arrows, you can search the command history by using the keyboard shortcuts CTRL+R (reverse search) and CTR +S (forward search). Press the key combination and start typing part of the command that you want to find in previously executed commands. The text you entered will be found in the command history in any position (unlike search in PowerShell using F8 or Shift+F8, which allows to look for the matches from the beginning of the line only). The PowerShell console should display the previous command corresponding to the search string. Line matches are highlighted in the command.

If the found command doesn’t suit you, to continue searching through the history, press CTRL+R/CTRL+S again. As a result, the following command corresponding to the search pattern will appear on the screen.

powershell command history bck-i-search

Using the F8 key, you can find the command in history that matches the text on the current command line. For example, enter get- and press F8. The last entry in the command history matching this text will be found. To go to the next command in history, press F8 again.

how to search powershell command history

You can also use the # character to search through the command history. For example, to find the last command that starts with Get-WMI, type #get-wmi and press the Tab key. The last command matching the pattern will appear in the console:

search commands in powershell history

The command history works the same in both classic Windows PowerShell and the new PowerShell Core (if you’ve already upgraded your PoSh version).

To get a list of previous PoSh command in the Notepad.exe window, run the command:

notepad (Get-PSReadLineOption | select -ExpandProperty HistorySavePath)

To display a list of commands in history that match a query, you can use:

Get-History | Select-String -Pattern "Get-"

powershell Get-History Select-String Pattern

Managing PowerShell Command History with the PSReadLine Module

The command history functionality in PowerShell 5.0 is not built into the Windows Management Framework itself, but is based on the third-party PSReadLine module, which significantly extends the functionality of the PowerShell console. PSReadLine highlights the syntax in the console, it is responsible for selection of the text with your mouse and copying/pasting it using CTRL+C and CTRL+V. This module in Windows 10 is located in the C:\Program Files\WindowsPowerShell\Modules\PSReadline folder and is automatically imported when the PowerShell console starts.

PSReadLine is not included into the standalone PowerShell 5.0 installer for previous versions of Windows. Thus, if you want to use the PowerShell command history functionality in previous Windows versions (Windows 7/8.1 and Windows Server 2008R2/2012R2), in addition to installing Windows Management Framework 5.1, you will need to install the PSReadLine module via the PackageManagement module (formerly OneGet) from the online repository using the command:

Install-Module PSReadLine

A complete list of functions of the PSReadLine module for managing the commands history in PowerShell and the keys assigned to them can be displayed with the command:

Get-PSReadlineKeyHandler | ? {$_.function -like '*hist*'}

Key       Function                Description
---       --------                -----------
UpArrow   PreviousHistory         Replace the input with the previous item in the history
DownArrow NextHistory             Replace the input with the next item in the history
Ctrl+r    ReverseSearchHistory    Search history backwards interactively
Ctrl+s    ForwardSearchHistory    Search history forward interactively
Alt+F7    ClearHistory            Remove all items from the command line history (not PowerShell history)
F8        HistorySearchBackward   Search for the previous item in the history that starts with the current input - like NextHistory if the input is empty
Shift+F8  HistorySearchForward    Search for the next item in the history that starts with the current input - like NextHistory if the input is empty
Unbound   ViSearchHistoryBackward Starts a new seach backward in the history.
Unbound   BeginningOfHistory      Move to the first item in the history
Unbound   EndOfHistory            Move to the last item (the current input) in the history
Get-PSReadlineKeyHandler

The command history can be configured using Get-PSReadlineOption and Set-PSReadlineOption cmdlets. Current PSReadline settings can be viewed using this command:

Get-PSReadlineOption | select HistoryNoDuplicates, MaximumHistoryCount, HistorySearchCursorMovesToEnd, HistorySearchCaseSensitive, HistorySavePath, HistorySaveStyle

Get-PSReadlineOption

The settings of the following PSReadline parameters can be important for us:

  • HistoryNoDuplicates – determines whether the same commands have to be saved;
  • MaximumHistoryCount – the maximum number of the stored commands (by default the last 4096 commands are saved);
  • HistorySearchCursorMovesToEnd — determines whether you have to go to the end of the command when searching;
  • HistorySearchCaseSensitive – determines whether search is case sensitive (PS command history is not case sensitive by default);
  • HistorySavePath – shows the path to the file in which the command is stored;
  • HistorySaveStyle – determines the peculiarities of saving commands:
    • SaveIncrementally — the commands are saved after they are run (by default);
    • SaveAtExit — the history is saved when the PowerShell console is closed;
    • SaveNothing — disable saving command history.

You can change the settings of PSReadLine module using the Set-PSReadlineOption. For example:

Set-PSReadlineOption -HistorySaveStyle SaveAtExit

Set-PSReadlineOption

To increase the number of PowerShell commands saved in the log file, run the command:

Set-PSReadlineOption -MaximumHistoryCount 10000

So, the ability to save the history of executed PowerShell commands is one of the arguments to prefer PoSh console to cmd.

How to Clear PowerShell Console History Commands?

As we explained above, the PSReadline module saves all the PowerShell console commands to a text file. However, in some cases, the administrator has to enter various sensitive information in the PowerShell console (credentials, passwords, addresses, personal data, etc.). Thus, another server administrator or attacker can access the history data in a plain text file. For security reasons, you might need to clear the history of the executed PowerShell commands or completely disable the command history.

The Clear-History cmdlet can only be used to clear the in-memory command history of the current PowerShell session. It clears only the list of previous commands that the Get-History cmdlet displays.

You can remove only one previous command from history:

Clear-History -count 1 -newest

Or clear all commands with a specific pattern:
Clear-History -CommandLine *set-ad*

To completely clear the history of previous PowerShell commands, you need to delete the ConsoleHost_history.txt file to which they are written by the PSReadline module. You can get the current PowerShell history file location and remove it with the command:

Remove-Item (Get-PSReadlineOption).HistorySavePath

After that, close the PowerShell console window.

If you want to completely disable saving the history of PowerShellcommands to a text file, run the command:

Set-PSReadlineOption -HistorySaveStyle SaveNothing

disable powershell comand history

How to Export/Import PowerShell Command History to Another Session?

Sometimes it is convenient to have the same set of frequently used PowerShell commands on different computers. You can export the current command history on your computer to an xml file and import it to other computers. Also this can be done by copying the ConsoleHost_history.txt file to user profiles on the desired computers.

To export commands from the current session to a file, you can use the Export-Clixml cmdlet:

Get-History | Export-Clixml -Path c:\ps\commands_hist.xml

To import command history from a file into another PoSh session (on a local or another computer):

Add-History -InputObject (Import-Clixml -Path c:\ps\commands_hist.xml)

export import powershell history

To automatically export the previous commands to a file at the end of a PowerShell session, you can bind the script to the PoSh session termination event (The session must be necessarily ended with the exit command, rather than simply closing the PowerShell window):

$HistFile = Join-Path ([Environment]::GetFolderPath('UserProfile')) .ps_history
Register-EngineEvent PowerShell.Exiting -Action { Get-History | Export-Clixml $HistFile } | out-null
if (Test-path $HistFile) { Import-Clixml $HistFile | Add-History }

Leave a Reply