Using Invoke-History in PowerShell
Welcome back to Wahmans PowerShell Blog! 🚀 Today’s cmdlet highlight is all about Invoke-History — a handy little tool in any PowerShell user’s arsenal. The official description from Microsoft says:
Invoke-History: Runs commands from the session history.
Whether you’re a beginner still getting comfortable with the shell, or a seasoned scripter optimizing your workflow, this command can be a real time-saver. Let’s explore how to use Invoke-History, starting with the basics and ramping up to more advanced examples.
What is PowerShell History?
Before we dive into the examples, here’s a quick overview: Every time you run a command in PowerShell, it’s stored in a session-based history list. You can view this history using the Get-History cmdlet. Each history entry is indexed with an ID that lets you re-run it later using Invoke-History.
Example 1: Re-run Your Last Command
This is the most basic usage. Just run:
Invoke-History
This re-runs the last command you executed. Perfect for when you forget to run as Administrator or miss a parameter and want to quickly correct it.
Example 2: Re-run a Specific Command by ID
First, check your command history using:
Get-History
Each entry has an ID. Let’s say you want to re-run command #15:
Invoke-History -Id 15
This is helpful when you want to repeat something you did earlier without retyping it.
Example 3: Assign History to a Variable and Inspect It
You can also get creative and capture a previous command for inspection or manipulation:
$cmd = Get-History | Where-Object CommandLine -like '*Get-Service*'
$cmd | Format-List
Great when you’re debugging or automating a workflow and want to know exactly what was run.
Example 4: Pipe History Command Output to Re-run Conditionally
Let’s say you want to re-run the last command that included a specific keyword, but only if it was within your last 10 commands:
$match = Get-History -Count 10 | Where-Object CommandLine -like '*Restart-Service*'
if ($match) {
Invoke-History -Id $match.Id
}
Amazing for automating repetitive operations with just a bit of logic.
Pro Tips
- Use
Ctrl + Rin the PowerShell console to reverse search your history interactively. - Use
Clear-Historyto wipe your session history if privacy or clutter is an issue.
That’s it for today’s post on Invoke-History! Whether you’re using it to repeat commands or scripting something more dynamic, it’s a great cmdlet to master.
Happy scripting, and I will see you in the next post!
Leave a Reply