By default, Windows saves all of the commands that you type in the PowerShell console to a text log file. This allows you to re-run any command and view the history of the PowerShell commands that you have run, even after you close the console or restart your computer. PowerShell currently uses two command history providers: the history of commands in the current session (displayed by the Get-History cmdlet) and a text log with previous commands that the PSReadLine module saves.
- Viewing PowerShell Command History on Windows
- How to Search in PowerShell Command History?
- Configure PowerShell Command History with the PSReadLine Module
- How to Run a PowerShell Command without Saving it to History?
- Using Predictive IntelliSense with PowerShell Command History
- How to Clear the Command History in PowerShell?
- How to Export/Import PowerShell Command History to Another Session?
Viewing PowerShell Command History on Windows
In the PowerShell console, the last command you typed appears when you press the Up key. If you continue to press the “up” key, you will see all the commands executed earlier. Thus, using the “Up arrow
” and “Down arrow
” keys you can scroll through the history of PowerShell commands and re-run previously typed commands. This is useful if you need to quickly execute one of the previous commands without typing it again.
The PowerShell console keeps a complete command history since Windows PowerShell 5.1 (installed by default in Windows 10). In previous versions of Windows PowerShell (and the cmd command prompt), the history of executed commands is available only in the current PowerShell session. Use the Get-History cmdlet to view the history of previous commands in the current session.
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 *
You can run the previous command by its ID:
Invoke-History 6
The command history is reset and the list in Get-History is cleared when you close the PowerShell console.
However, Windows PowerShell 5.1 and PowerShell Core also save the last 4096 commands in a plain text file in each user’s profile %userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt
.
You can open this file and view the command history using any text editor. For example, to open a command log file using Notepad:
notepad (Get-PSReadLineOption | select -ExpandProperty HistorySavePath)
The history log is kept separately for the PowerShell console and for PowerShell ISE.
doskey /history
The F7
key is used to search through cmd history.
How to Search in 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 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 looking 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.
Press CTRL+R
/CTRL+S
again to continue searching the history if the found command is not what you want. As a result, the following command corresponding to the search pattern will appear on the screen.
Using the F8
key, you can search for the command in history that matches the text on the current command line. For example, type 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.
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:
winget install --id=Microsoft.PowerShell -e
To display a list of commands in history that match a query, you can use:
Get-History | Select-String -Pattern "Get-"
And grep the results using the pipe:
Get-Content (Get-PSReadlineOption).HistorySavePath| Select-String -Pattern "Get-"
Configure PowerShell Command History with the PSReadLine Module
The command history functionality in PowerShell is not built into the Windows Management Framework itself but is based on the PSReadLine module, which greatly enhances the functionality of the PowerShell console. The PSReadLine module on Windows is located in C:\Program Files\WindowsPowerShell\Modules\PSReadline folder and is automatically imported when you start the PowerShell console.
CTRL+C
and CTRL+V
.Check that the module is loaded into your current PowerShell session:
Get-Module
If the PSReadline module is not loaded, verify that it is installed. If necessary, install it from the PowerShell Gallery online repository:
Get-Module -ListAvailable | where {$_.name -like "*PSReadline*"}
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
List the current PowerShell command history settings in the PSReadLine module:
Get-PSReadlineOption | select HistoryNoDuplicates, MaximumHistoryCount, HistorySearchCursorMovesToEnd, HistorySearchCaseSensitive, HistorySavePath, HistorySaveStyle
You may want to consider the following PSReadline parameters:
- HistoryNoDuplicates – 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 — whether it is necessary to jump to the end of the command when searching;
- istorySearchCaseSensitive – whether a search is case sensitive (PowerShell command history is not case sensitive by default);
- HistorySavePath – path to a text file where the history of PowerShell commands is stored;;
- HistorySaveStyle – command history saving options:
- SaveIncrementally — the commands are saved when executed (by default);
- SaveAtExit —the history is saved when you close the PowerShell console;
- SaveNothing — disable saving command history.
You can change the PSReadLine module settings with the Set-PSReadlineOption command. For example, to increase the number of PowerShell commands stored in the log:
Set-PSReadlineOption -MaximumHistoryCount 10000
If you want to save not only the executed commands but also their output in the PowerShell command history, you can enable command transcription. Just add the following function to the user’s PowerShell profile (notepad $profile.CurrentUserAllHosts
):
Function StartTranscript {
Trap {
Continue
}
$TranScriptFolder = $($(Split-Path $profile) + '\TranscriptLog\')
if (!(Test-Path -Path $TranScriptFolder )) { New-Item -ItemType directory -Path $TranScriptFolder }
Start-Transcript -Append ($($TranScriptFolder + $(get-date -format 'yyyyMMdd-HHmmss') + '.txt')) -ErrorVariable Transcript -ErrorAction stop
}
StartTranscript
The user profile now contains a detailed log file for each PowerShell session in the %USERPROFILE%\Documents\WindowsPowerShell\TranscriptLog
directory.
How to Run a PowerShell Command without Saving it to History?
In the Linux bash shell, you can disable history for commands starting with spaces (with HISTCONTROL= ignorespace
). You can configure similar behavior for PowerShell.
To do this, add the following code to the current user’s PowerShell profile ( $profile.CurrentUserAllHosts
):
Set-PSReadLineOption -AddToHistoryHandler { param($command) if ($command -like ' *') { return $false } return $true }
Set-ExecutionPolicy Remotesigned
Now, just start your command with a space if you don’t want it to be saved in the PowerShell command history.
Also, starting with the Readline v2.0.4 module version, commands containing the following keywords are automatically ignored and not saved to the history: Password
, Asplaintext
, Token
, Apikey
, Secret
.
Using Predictive IntelliSense with PowerShell Command History
A new PowerShell Predictive IntelliSense feature is available in PSReadLine 2.2.2+. This feature displays the most appropriate commands from the local command history when you type a command in the PowerShell console.
In this example, I typed get-wm
in the console, and Predictive IntelliSense suggested one of the commands I typed earlier that matched my input. If this command suits me, I need to press the right arrow key
to accept this command and not type the rest of the characters manually.
By default, Predictive IntelliSense hints are displayed in gray text and are difficult to read against the black background of the PowerShell console. This command makes the suggested text more contrasting:
Set-PSReadLineOption -Colors @{ InlinePrediction = '#7A957B'}
Set-PSReadLineOption -PredictionSource History
To reset the IntelliSense predictive suggestion, press the Esc key.
You can switch to another view by pressing the F2 key. Now, instead of displaying one most appropriate command (InlineView
), a drop-down list with all similar commands will be displayed (ListView
).
Use the up/down keys to quickly select a command you need from the command history.
How to Clear the Command History in PowerShell?
As we explained above, the PSReadline module saves all PowerShell console commands to a text file. However, in some cases, the administrator has to enter various sensitive information into the PowerShell console (credentials, passwords, tokens, addresses, personal data, etc.). History data in a plain text file can be accessed by another server administrator or attacker. For security reasons, you might have to clear the history of the PowerShell commands that you have run or turn off the command history completely.
The Clear-History cmdlet allows you to clear the history of commands only in the current PowerShell session. It only deletes the previous command list that Get-History returns.
You can remove only one previous command from the 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 that the PSReadline module writes to. 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 PowerShell commands to a text file, run the command:
Set-PSReadlineOption -HistorySaveStyle SaveNothing
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. You can do this by copying the ConsoleHost_history.txt file in the user’s profile to the target computers.
You can also use the Export-Clixml
cmdlet
to export command history from the current session to a text file:
Get-History | Export-Clixml -Path c:\ps\commands_hist.xml
To import command history from a file into another PowerShell session (on a local computer or on a different computer):
Add-History -InputObject (Import-Clixml -Path c:\ps\commands_hist.xml)
To automatically export the previous commands to a file when the PowerShell session ends, you can bind the script to the PoSh session end event (!! The session must be terminated with the exit
command, r, not by simply closing the PowerShell console):
$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 }
6 comments
So, is this a PowerShell 5 feature, or a Windows 10 feature? I’m asking because I installed WMF 5 on Windows 7 (KB3134760), and even though it’s now been upgraded to PowerShell 5 (confirmed by $PSVersionTable.psversion), I’m still finding no trace of the history file.
Additionally, you need to install PSReadLine module (ncluded in Windows 10).
For example, using PowerShell Get (available in PowerShell v5 and Windows Management Framework 5):
Install-Module PSReadLine
[…] If you want more information, and also how to change the default settings, see the blog: https://woshub.com/powershell-commands-history/ […]
[…] I am not aware that from Powershell version 5 previously executed commands are automatically stored in the location %userprofile%AppDataRoamingMicrosoftWindowsPowerShellPSReadlineConsoleHost_history.txt until I saw the blog https://woshub.com/powershell-commands-history/ […]
thank you, very useful!
Here’s a small PowerShell function to get and select a command from your console history.
_https://jdhitsolutions.com/blog/powershell/8777/copy-powershell-history-command/