Access and Manage Your Console History

1. Problem

After working in the shell for a while, you want to invoke commands from your history, view your command history, and save your command history.

2. Solution

The shortcuts given in Section 1.12, “Customize the Shell to Improve Your Productivity” let you manage your history, but PowerShell offers several features to help you work with your console in even more detail.

To get the most recent commands from your session, use the Get-History cmdlet:

        Get-History

To rerun a specific command from your session history, provide its Id to the Invoke-History cmdlet:

        Invoke-History 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 Get-History to the Export-CliXml cmdlet:

        Get-History | Export-CliXml Filename

To add a previously saved command history to your current session history, call the Import-CliXml cmdlet and then pipe that output to the Add-History cmdlet:

        Import-CliXml Filename | Add-History


3. Discussion

Unlike the console history hotkeys discussed in Section 1.12, “Customize the Shell to Improve Your Productivity” the Get-History 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 Get-History), you can pass it to Invoke-History to execute that command again. The example prompt function shown in Section 1.3, “Customize Your Shell, Profile, and Prompt” makes working with prior history items easy—as the prompt for each command includes the history ID that will represent it.

The IDs provided by the Get-History 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.

Tags: , , , , , ,