Invoke History - PowerShell


Overview

Invoke-History is a PowerShell command that allows you to repeat or modify previously executed commands from the command history. It provides a convenient way to re-run commands, explore command history, and troubleshoot scripts.

Syntax

Invoke-History [-Command] <CommandNumber> [-Modify] [-Script] [-UseOriginalArgumentValues] [-UseVariableValuesAtInvocationTime] [-WhatIf] [-Confirm]

Options/Flags

  • -Command: Specifies the command number to be executed or modified.
  • -Modify: Allows you to make modifications to the specified command before invoking it.
  • -Script: Executes the specified command as a script block.
  • -UseOriginalArgumentValues: Uses the original argument values from the history command rather than modified values.
  • -UseVariableValuesAtInvocationTime: Uses the variable values at the time of invocation rather than when the command was originally executed.
  • -WhatIf: Shows what would happen if the command were invoked without actually executing it.
  • -Confirm: Prompts you for confirmation before invoking the command.

Examples

Re-execute command number 10:

Invoke-History 10

Modify and re-execute command number 15:

Invoke-History 15 -Modify {$_.Arguments.Add("new_argument")}

Execute command number 20 as a script block:

Invoke-History 20 -Script

Display command number 25 without invoking it:

Invoke-History 25 -WhatIf

Common Issues

  • If the specified command number does not exist, Invoke-History will return an error.
  • When using -Modify, be careful not to alter command syntax in a way that breaks its execution.
  • Using -Script can lead to unexpected behavior if the command relies on variables not available in the current scope.

Integration

Invoke-History can be used in combination with other PowerShell commands, such as:

  • Get-History: Retrieves the command history.
  • Out-File: Logs the modified command to a file.
  • Invoke-Expression: Evaluates the modified command as an expression.
  • Get-History
  • Invoke-Command
  • Repeat-Command