A better Get-History

by Aug 22, 2017

When you type “h” in PowerShell, you see the history of commands you entered during your session. Inspired by Pratek Singh (https://geekeefy.wordpress.com/2017/06/20/powershell-get-history/), here is a clever alternative called “h+” that opens up a grid view window instead and lets you pick the commands from your history. Hold CTRL to select multiple items.

Pratek invoked all selected items using Invoke-Expression. This can be dangerous, and it won’t echo the commands, so you don’t really know what was executed. In “h+”, that’s why all selected items are placed into the clipboard. From there, you choose what to do: you can paste them into documentations, or paste them back into PowerShell to execute them. Even when you paste them back into PowerShell, you get the chance to review the commands before you press ENTER to run them.

Function h+ 
{
    Get-History |
      Out-GridView -Title "Command History - press CTRL to select multiple - Selected commands copied to clipboard" -OutputMode Multiple |
      ForEach-Object -Begin { [Text.StringBuilder]$sb = ""} -Process { $null = $sb.AppendLine($_.CommandLine) } -End { $sb.ToString() | clip }
}

Simply add the h+ function to your profile script (path found in $profile) to have it handy at all times.

Twitter This Tip! ReTweet this Tip!