Problem
After working in the shell for awhile, you want to invoke commands from your history, view your command history, and save your command history.
Solution
To get the most recent commands from your session, use the GetHistory cmdlet:
GetHistory
To rerun a specific command from your session history, provide its Id to the InvokeHistory cmdlet: InvokeHistory Id
To increase (or limit) the number of commands stored in your session history, assign a new value to the $MaximumHistoryCount variable: $MaximumHistoryCount = Count
To save your command history to a file, pipe the output of GetHistory to the ExportCliXml cmdlet:
GetHistory | ExportCliXml Filename
To add a previously saved command history to your current session history, call the ImportCliXml cmdlet and then pipe that output to the AddHistory cmdlet:
ImportCliXml Filename | AddHistory
Discussion
Unlike the console history hotkeys the GetHistory cmdlet produces rich objects that represent information about items in your history. Each object contains that item’s ID, command line, start of execution time, and end of execution time.
Once you know the ID of a history item (as shown in the output of GetHistory), you can pass it to InvokeHistory to execute that command again.
The IDs provided by the GetHistory cmdlet differ from the IDs given by the Windows console common history hotkeys (such as F7), because their history management techniques differ.
By default, PowerShell stores only the last 64 entries of your command history. If you want to raise or lower this amount, set the $MaximumHistoryCount variable to the size you desire. To make this change permanent, set the variable in your PowerShell profile script. To clear your history, either restart the shell, or temporarily set the $MaximumHistoryCount variable to 1.