Giving PowerShell a Persistent History of Commands

 

If you are disappointed that neither Command Prompt nor PowerShell on Windows have the ability to maintain a persistent command history the same way the Linux Terminal does by default, then this blog post is for you.

If you would like to add this capability to the Command Prompt, then the easiest way is to install either of the following applications:

If you would like to add this capability to PowerShell, then follow the following steps:

Open PowerShell in administrator mode and find out which version of PowerShell you have by running for following command:

  • $PSVersionTable.PSVersion

If you have a version that is less than 3, then you need to update your PowerShell. To update to version 3, you must download the Windows Management Framework 3: http://www.microsoft.com/en-us/download/details.aspx?id=34595, then choose either the x86 or the x64 files depending on your system. For x64, I downloaded Windows6.1-KB2506143-x64.msu, Windows6.0-KB2506146-x64.msu

Allow PowerShell to import or use scripts including modules by running the following command:

  • set-executionpolicy remotesigned

Install PsGet by executing the following commands:

Install PSReadline by executing the following command:

  • install-module PSReadline

Open notepad (or better notepad++) in administrator mode and type the following script:

  • $HistoryFilePath = Join-Path ([Environment]::GetFolderPath('UserProfile')) .ps_history
  • Register-EngineEvent PowerShell.Exiting -Action { Get-History | Export-Clixml $HistoryFilePath } | out-null
  • if (Test-path $HistoryFilePath) { Import-Clixml $HistoryFilePath | Add-History }
  • # if you don't already have this configured...
  • Set-PSReadlineKeyHandler -Key UpArrow -Function HistorySearchBackward
  • Set-PSReadlineKeyHandler -Key DownArrow -Function HistorySearchForward

Save the file as C:\Users\<username>\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1, where you should replace <username> with the correct folder name on your PC. Do not forget to change the “save as type” option to all files.

Close PowerShell and open it again so that it starts using the script we saved.

From now on, PowerShell will keep the last few hundred commands you typed in its history. Try entering a few commands, and then run the following command to see PowerShell’s history of commands:

  • get-history

Close PowerShell, and then open it again. Enter a few more commands, and then the get-history command. You will see last session’s commands as well as the current session’s commands are there.

You can also scroll through the all your history of commands by using up and down arrow buttons!

Para obter informações mais completas sobre otimizações do compilador, consulte nosso aviso de otimização.