PowerShell 2.0: One Cmdlet at a Time 64 Clear-History

Continuing the series looking at new cmdlets available in PowerShell 2.0. This time we look at the Clear-History cmdlet.

What can I do with it?

Remove commands from the history of those entered in the current session. PowerShell has two places where a history of the commands you have entered are kept. Within the console you can use F7 to view them and Alt-F7 to clear that list. There are also some cmdlets for managing PowerShell history, such as Get-History and the new Clear-History.

Example:

Check current history. Then remove any commands from the history which contain the string set.

Get-History Clear-History -CommandLine *set*

The initial history is as below:

Now we remove any commands from the history which contain the string set. You can see they have been removed and the others remain.

How could I have done this in PowerShell 1.0?

Andrew Watt explains how you can clear history in PowerShell 1.0 on this forum post.

From a new session, set the inbuilt $MaximumHistoryCount variable to 1.0, then get the current history and export it to XML.

$MaximumHistoryCount = 1 Get-History | Export-Clixml “History.xml”

Edit the XML document, remove the text between and replace it with “No commands have been entered”

Create a script called Empty-TheHistory.ps1 containing the below:

function global:Empty-History{ $MaximumHistoryCount = 1 Import-Clixml “History.xml” | Add-History }

Now dot source the script and use the Empty-History function to clear your history.

1000 things 1% better!