powershellwindows-terminalcommand-history

Able to persist powershell commands sent via windows terminal


I am opening a new powershell tab in Windows Terminal via a script, which launches a specific command. When I press the "up" arrow, that command I've sent in the script is not persisted in powershell's history. The only commands persisted are those in my history, and those that have occurred after the tab has opened and run.

Is there a way to persist this command (in this case lazygit) to powershell's history so I can access it by simply using the "up" arrow once the app is closed?

wt -d "d:/git/" powershell -NoExit lazygit

Solution

  • Preface:


    Mathias, in a comment on the question, correctly points out that adding a command to PSReadLine's command history as part of a PowerShell CLI call is not an option, because PSReadLine, the bundled module that facilitates the interactive command-line editing experience, isn't yet initialized at the time the command passed to the CLI executes.

    However, you can manually append a command to PSReadLine's history file before making a CLI call, which will then be offered as the first one in the history recall, e.g.:

    $cmd = 'lazygit'
    $cmd | Add-Content (Get-PSReadLineOption).HistorySavePath
    wt -d 'd:/git' powershell -NoExit $cmd
    

    Note:


    Generalized variant of the solution above:
    # Use a sample command that involves both the following embedded chars: ; "
    $cmd = 'Write-Output "Hello, World"; Get-Date'
    
    # Save the command as-is to PSReadLine's history.
    $cmd | Add-Content (Get-PSReadLineOption).HistorySavePath
    
    # For use on the command line the embedded chars. need *escaping*.
    # (The -d option for setting the working dir. is omitted for brevity.)
    wt.exe powershell -NoExit -Command (
      $cmd -replace ';', '\;' -replace '"', ('{0}"' -f ('\' * (3, 1)[[int] $IsCoreClr]))
    )
    

    Note:


    [1] The automatic $IsCoreCLR variable is used to distinguish between the two editions. Strictly speaking, PowerShell (Core) 7 versions up to v7.2.x behaved the same as Windows PowerShell with respect to embedded " chars., but these versions are no longer supported. The extra \ instances are needed when calling from Windows PowerShell due to a long-standing bug - see this answer - that won't be fixed in that edition, which will see only fixes that are both security-critical and don't break backward compatibility.