Copy Command History to a Script

by Mar 15, 2016

Sometimes you may have played around with the interactive PowerShell and suddenly realized that some of the commands you played with were pretty useful. Wouldn't it be nice to be able to copy the entire command line history to a script?

In the PowerShell ISE, this is easy–because it is extensible. Here is a script that adds a new menu command called Copy History (you can invoke the command with CTRL+ALT+H):

function Copy-HistoryToISE 
  $file = $psise.CurrentPowerShellTab.Files.Add()
  $file.Editor.Text = (Get-History | Where-Object ExecutionStatus -eq Completed).CommandLine 

$psise.CurrentPowerShellTab.AddOnsMenu.Submenus.Add('Copy History', { Copy-HistoryToISE }, 'CTRL+ALT+H') 

Once you run the command, all of your interactive commands that completed successfully will be copied to a new ISE script pane. Any command that errored out will be excluded. You only get back the commands that actually worked.

Twitter This Tip! ReTweet this Tip!