Exploring PowerShell’s Get-History Cmdlet
Welcome back to Wahmans PowerShell Blog! Today, we’re diving into a simple yet powerful cmdlet: Get-History. This cmdlet is part of PowerShell’s core tools and serves a fundamental role in aiding productivity and session diagnostics. Let’s explore what it does and how you can make the most of it.
What Does Get-History Do?
According to Microsoft Docs, the Get-History cmdlet:
“Gets a list of the commands entered during the current session.”
Essentially, this cmdlet gives you access to the command history of your current PowerShell session—allowing you to review, reuse, and troubleshoot commands you’ve previously run.
Example 1: Basic Use – View Your Command History
If you’re just getting started, you can type the following command to display your session’s history:
Get-History
This returns a list of previously run commands, allowing you to scroll through and see what you’ve executed so far in your session.
Example 2: Re-Run a Specific Command
Each command in the history has an ID. You can use that ID with the Invoke-History cmdlet to re-run a specific command. Let’s say you want to re-run command number 12:
Invoke-History -Id 12
This saves time, especially when dealing with longer or more complex commands.
Example 3: Exporting History to a File
Maybe you want to save your session history for documentation or future reference. You can export it like this:
Get-History | Export-Clixml -Path "$HOME\ps_history.xml"
This creates a file containing your history in XML format, which can later be imported back into a session if needed.
Example 4: Advanced Use – Filtering and Auditing Commands
For more advanced use cases, like security auditing or debugging scripts, you might want to filter the history. For example, to find all commands that involved the FileSystem provider:
Get-History | Where-Object { $_.CommandLine -match "Get-ChildItem" }
This filters out commands based on patterns, keywords, or specific cmdlets used—very useful for larger sessions or security logs.
Wrapping Up
The Get-History cmdlet is a versatile and often underused tool that can greatly enhance your efficiency in PowerShell. Whether you’re a beginner looking to learn from your past commands or an advanced user tracking session behavior, this cmdlet has something to offer.
Happy scripting, and I will see you in the next post!
Leave a Reply