Windows OS Hub
  • Windows Server
    • Windows Server 2022
    • Windows Server 2019
    • Windows Server 2016
    • Windows Server 2012 R2
    • Windows Server 2008 R2
    • SCCM
  • Active Directory
    • Active Directory Domain Services (AD DS)
    • Group Policies
  • Windows Clients
    • Windows 11
    • Windows 10
    • Windows 8
    • Windows 7
    • Windows XP
    • MS Office
    • Outlook
  • Virtualization
    • VMWare
    • Hyper-V
    • KVM
  • PowerShell
  • Exchange
  • Cloud
    • Azure
    • Microsoft 365
    • Office 365
  • Linux
    • CentOS
    • RHEL
    • Ubuntu
  • Home
  • About

Windows OS Hub

  • Windows Server
    • Windows Server 2022
    • Windows Server 2019
    • Windows Server 2016
    • Windows Server 2012 R2
    • Windows Server 2008 R2
    • SCCM
  • Active Directory
    • Active Directory Domain Services (AD DS)
    • Group Policies
  • Windows Clients
    • Windows 11
    • Windows 10
    • Windows 8
    • Windows 7
    • Windows XP
    • MS Office
    • Outlook
  • Virtualization
    • VMWare
    • Hyper-V
    • KVM
  • PowerShell
  • Exchange
  • Cloud
    • Azure
    • Microsoft 365
    • Office 365
  • Linux
    • CentOS
    • RHEL
    • Ubuntu

 Windows OS Hub / PowerShell / Using Previous Command History in PowerShell Console

January 31, 2023 PowerShellWindows 10Windows 11Windows Server 2019

Using Previous Command History in PowerShell Console

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.

Contents:
  • 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 *

powershell get-history

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)

powershell view consolehost-history log file

The history log is kept separately for the PowerShell console and for PowerShell ISE.

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 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 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 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.

powershell command history bck-i-search

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.

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).  You can use the built-in WinGet package manager in Windows 11 and Windows 10 to quickly update your version of PowerShell:

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:

Get-Content (Get-PSReadlineOption).HistorySavePath| Select-String -Pattern "Get-"

powershell Get-History Select-String Pattern

The Select-String cmdlet can be used in PowerShell just like the grep command in Linux.

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.

PSReadLine provides syntax highlighting in the console, is responsible for the ability to use text selection with the mouse and its copy/paste using CTRL+C and CTRL+V.

Check that the module is loaded into your current PowerShell session:

Get-Module

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

You can also manually install the PowerShell module offline.

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

List the current PowerShell command history settings in the PSReadLine module:

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

Get-PSReadlineOption

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

Enable PowerShell History with detailed Transcript

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
} 

dont save command with front space to powershell history

This feature requires that you set the PowerShell Execution policy on your computer to Remotesigned:

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. At the same time, cmdlets from the SecretManagement password management module are considered safe and allowed to be saved to the history file.

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.

Using PowerShell Predictive Intellisense

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'}

Since PSReadLine 2.2.6, Predictive IntelliSense is enabled by default. You can enable it manually:

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).

Lixt Predictive IntelliSense command suggestions from PowerShell history

Use the up/down keys to quickly select a command you need from the command history.

Predictive IntelliSense works in the standard pwsh.exe/powershell.exe command line, as well as in the Windows Terminal and Visual Studio code.

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

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. 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)

export import powershell history

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
4
Facebook Twitter Google + Pinterest
previous post
How to Install the PowerShell Active Directory Module and Manage AD
next post
Join a Windows Computer to an Active Directory Domain

Related Reading

How to Connect VPN Before Windows Logon

November 14, 2023

Using WPAD (Web Proxy Auto-Discovery Protocol) on Windows

November 7, 2023

Send Emails with Microsoft Graph API and PowerShell

November 6, 2023

Zabbix: How to Get Data from PowerShell Scripts

October 27, 2023

Tracking Printer Usage with Windows Event Viewer Logs

October 19, 2023

6 comments

Bob April 2, 2016 - 5:43 pm

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.

Reply
Max April 4, 2016 - 7:59 am

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

Reply
PowerShell Command History | Virtual Allan November 10, 2018 - 10:54 am

[…] If you want more information, and also how to change the default settings, see the blog: https://woshub.com/powershell-commands-history/ […]

Reply
PowerShell Previous command history details | Hareesh Jampani March 6, 2019 - 7:49 am

[…] 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/ […]

Reply
Juan January 7, 2020 - 12:33 am

thank you, very useful!

Reply
serg April 30, 2022 - 2:15 pm

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/

Reply

Leave a Comment Cancel Reply

Categories

  • Active Directory
  • Group Policies
  • Exchange Server
  • Microsoft 365
  • Azure
  • Windows 11
  • Windows 10
  • Windows Server 2022
  • Windows Server 2019
  • Windows Server 2016
  • PowerShell
  • VMWare
  • Hyper-V
  • Linux
  • MS Office

Recent Posts

  • How to Connect VPN Before Windows Logon

    November 14, 2023
  • Removing Azure Arc Setup Feature on Windows Server 2022

    November 9, 2023
  • Using WPAD (Web Proxy Auto-Discovery Protocol) on Windows

    November 7, 2023
  • Send Emails with Microsoft Graph API and PowerShell

    November 6, 2023
  • Zabbix: How to Get Data from PowerShell Scripts

    October 27, 2023
  • Tracking Printer Usage with Windows Event Viewer Logs

    October 19, 2023
  • PowerShell: Configure Certificate-Based Authentication for Exchange Online (Azure)

    October 15, 2023
  • Reset Root Password in VMware ESXi

    October 12, 2023
  • How to Query and Change Teams User Presence Status with PowerShell

    October 8, 2023
  • How to Increase Size of Disk Partition in Ubuntu

    October 5, 2023

Follow us

  • Facebook
  • Twitter
  • Telegram
Popular Posts
  • Fix: Remote Desktop Licensing Mode is not Configured
  • Configuring Port Forwarding in Windows
  • Manage Windows Updates with PSWindowsUpdate PowerShell Module
  • Start Menu or Taskbar Search Not Working in Windows 10/11
  • How to Install Remote Server Administration Tools (RSAT) on Windows
  • How to Delete Old User Profiles in Windows
  • Adding Drivers into VMWare ESXi Installation Image
Footer Logo

@2014 - 2023 - Windows OS Hub. All about operating systems for sysadmins


Back To Top