Add-History

Add-History: Working with PowerShell Session History

Welcome back to Wahman’s PowerShell blog! In today’s post, we’ll dive into the Add-History cmdlet — a lesser-known, but incredibly useful tool in your PowerShell toolkit. According to Microsoft’s documentation, this cmdlet is used to append entries to the session history. In short, it gives you more control over the commands that are stored in your PowerShell session’s history.

Let’s break it down with some examples, starting with beginner use-cases and building up to more advanced scenarios.

📘 Example 1: Adding a Single Command to History

This is a simple example of manually appending a single command to your session history:

$historyItem = New-Object System.Management.Automation.HistoryInfo (0, 'Get-Process', (Get-Date))
Add-History -InputObject $historyItem

This adds the Get-Process command to your session history even though you didn’t execute it directly. Handy for keeping track of command ideas or skipped steps.

📘 Example 2: Re-Adding the Last Command

Say you want to repeat your last command later in the session. You can retrieve and re-add it to the history using:

$lastCommand = Get-History | Select-Object -Last 1
Add-History -InputObject $lastCommand

This is particularly helpful if you’re programmatically generating command history for replay or testing.

📘 Example 3: Add Multiple Commands to History from a Log File

Perhaps you store useful commands in a file. You can populate your session history by importing them:

$commands = Get-Content -Path ".\MyCommandLog.txt"
$counter = (Get-History | Measure-Object).Count + 1
foreach ($cmd in $commands) {
    $historyItem = New-Object System.Management.Automation.HistoryInfo ($counter, $cmd, (Get-Date))
    Add-History -InputObject $historyItem
    $counter++
}

This way, you can set up a repeatable environment from previous PowerShell work sessions.

📘 Example 4: Capture Executed Commands to Share with a Team

If you want to document all commands for an automation task and share them with coworkers:

# Run and store history during a session
Invoke-Command -ScriptBlock {
    Get-Service
    Get-EventLog -LogName Application -Newest 5
}

# Capture all commands from history
$myHistory = Get-History
$myHistory | ForEach-Object {
    Add-History -InputObject $_
    $_.CommandLine | Out-File -FilePath ".\TeamScriptLog.txt" -Append
}

Now your team has a reproducible script log to audit or rerun as needed.


The Add-History cmdlet may not be a daily tool for everyone, but it’s a powerful way to construct, manipulate, and share PowerShell sessions. Whether you’re operating interactively or building advanced automation scripts, managing your session history can greatly optimize your debugging and reproducibility processes.

🧑‍💻 Happy scripting, and I will see you in the next post!

Leave a Reply

Your email address will not be published. Required fields are marked *