Bagikan melalui


Using the Add-History Cmdlet

Restoring a Previously-Saved Windows PowerShell History

So you’re working in Windows PowerShell and you’ve just typed in a series of commands that perform a very useful task. Those commands are saved in the Windows PowerShell history, but now it’s time to go home. As you know, the moment you exit the Windows PowerShell console that history will be erased. In turn, that can mean only one thing: the next time you want to carry out that same task you’ll have to remember - and re-type - all those commands.

Or will you? Suppose - just suppose - that before you exit PowerShell you use this command to save your current history as an XML file named C:\Scripts\My_History.xml:

Get-History | Export-Clixml "c:\scripts\my_history.xml"

Why bother saving your Windows PowerShell history? Here’s why. The next time you fire up Windows PowerShell you can use the Import-Clixml cmdlet to reload that XML file. Once you’ve done that you can then pass the contents of that file to the Add-History cmdlet. Lo and behold, at that point your old history (the set of commands saved in My_History.xml) will magically be restored to your current history. Here’s what the command to do that looks like:

Import-Clixml "c:\scripts\my_history.xml" | Add-History

Maybe one of those cool before and after picture sets will help. Let’s suppose we conducted a Windows PowerShell session and, at the end, exported the history file. We now start a brand-new Windows PowerShell session; because we haven’t done anything yet, the history is blank:

Next we import the saved history file and call the Add-History cmdlet. Now take a look at the Windows PowerShell history:

It’s the next-best thing to having your own time machine!