making better use of powershell history

1 minute read

a screenshot

The native powershell Get-History cmdlet returns results from the open console only and this history is lost when you close that console. But similarly to .bash_history in Linux, the command line property from the Get-History output are also written to a file called Console_history.txt, which is useful as a more persistent history.

function hist

I added this to my powershell profile to make using Console_history.txt more fun:

$history = "~\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt" 
function hist {get-content $history -tail 512}


the hist function gives me quick access to the contents of my Console_history.txt

function save-cmd

Often I want to save the command I have just run for later use, but I don’t want to leave the console and break my concentration. I added save-cmd function my $Profile to pull the last item in my history, and save it to a file in my personal powershell repo. I can retrieve the content of this file with the shist function.

$shist = "~\Documents\GitLab\powershell\consolehistory_saved.txt"
function shist {Get-Content $shist}
function save-cmd { (get-history | Select-Object -Last 1).commandline | out-file -FilePath $hist -Append -NoClobber -Force }


The command below will add the last item in your history to your $Profile

(get-history | Select-Object -Last 1).commandline | out-file -FilePath $profile -Append -Force -NoClobber -Encoding utf8 ; & $Profile

go deeper

What will I find if I search the PSGallery for items related to “history”?

Find-Script *history* | Select-Object name, Author, CompanyName,description
Name                   Author         CompanyName Description
----                   ------         ----------- -----------
Invoke-SelectedHistory Jeffrey Snover jsnover     Show the command line history and Invoke the selected items


written by Mr. Monad Manifesto!

Find-Script *history* | Save-Script -Path . -Force
cat .\Invoke-SelectedHistory.ps1

.DESCRIPTION
   Show the command line history and Invoke the selected items

.DESCRIPTION
   Essentially this does:
    PS> Get-History -count:$count | Out-Gridview -Passthru | Invoke-History

   The benefit is that you can do searching and multiple selections.
.EXAMPLE
   PS> ISH -count 200 -verbose

pretty neat alias in that script: ISH

lessons learned..

I should have searched PSGallery earlier. I plan to modify this script so that instead of pulling from Get-History, it pulls from a csv which will contain my Save-Cmd output. I’ll have to also modify my Save-Cmd function so that it stores the object output of get-history instead of just the command line. Then i can make use of the gui and invoke-command feature in jsnover’s script to work as a cool launcher for saved one-liners.

Leave a Comment