Get History - PowerShell


Overview

Get-History retrieves a list of previously executed commands from the current PowerShell session. It allows you to review your command history, re-execute commands, and troubleshoot errors in scripts.

Syntax

Get-History [-Count] <NumberOfRecords> [-Filter] <FilterString>
[-UseOriginalHistoryFile] [-OutputFile] <FilePath> [-RedirectOutput]

Options/Flags

| Option/Flag | Purpose | Default Value |
|—|—|—|
| -Count | Specifies the number of records to retrieve. | 30 |
| -Filter | Filters the history based on a specified string. | None |
| -UseOriginalHistoryFile | Loads the command history from the original Windows PowerShell history file instead of the current session’s memory. | False |
| -OutputFile | Saves the history to a specified file. | None |
| -RedirectOutput | Redirects the output to a file instead of displaying it in the console. | False |

Examples

Example 1: Displaying the last 10 commands

Get-History -Count 10

Example 2: Filtering the history

Get-History -Filter "ls*"

Example 3: Saving the history to a file

Get-History -OutputFile "myhistory.txt"

Common Issues

  • History is not displayed: If the -UseOriginalHistoryFile parameter is not specified, the command will only retrieve the history from the current session’s memory. To view the complete history, including commands from previous sessions, use -UseOriginalHistoryFile.

Integration

Get-History can be integrated with other PowerShell commands for advanced tasks. For example, you can pipe the output of Get-History to Out-File to save the history for later use.