Skip to content

Instantly share code, notes, and snippets.

@Jaykul
Last active April 5, 2024 16:45
Show Gist options
  • Save Jaykul/7dee4f47a61616fde6858ca960743fd5 to your computer and use it in GitHub Desktop.
Save Jaykul/7dee4f47a61616fde6858ca960743fd5 to your computer and use it in GitHub Desktop.
How to inject text into the NEXT command prompt
$global:Suggestion = Get-Completion "This is my question"
$global:InjectCommand = Register-EngineEvent -SourceIdentifier PowerShell.OnIdle {
[Microsoft.PowerShell.PSConsoleReadLine]::Insert($global:Suggestion)
Stop-Job $global:InjectCommand # This removes the event
}

Thanks to PSReadLine's events, it is not hard to write a PowerShell command that can generate and inject text into the next command prompt, allowing you to edit it and run it.

There is something like this in the ReadLine AI project, and since someone asked how to do it on Mastodon, I thought I'd distill it here.

The scary version is to prepare the text in a variable (e.g. $Suggestion) and then register a handler for OnIdle so that when the prompt finishes rendering, your text will be injected for the user to run.

The version in ReadLine AI actually registers a hotkey instead, which allows it to read what you've written so far, get a completion, and then update the current command, instead of the next command.

Set-PSReadLineKeyHandler -Chord Ctrl+G -ScriptBlock {
$line = $null
$cursor = $null
[Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor)
# get response from create_completion function
$completion = Get-Completion $line
# check if output is not null
if ($completion -ne $null) {
foreach ($str in $completion) {
if ($str -ne $null -and $str -ne "") {
[Microsoft.PowerShell.PSConsoleReadLine]::AddLine()
[Microsoft.PowerShell.PSConsoleReadLine]::Insert($str)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment