Skip to content

Instantly share code, notes, and snippets.

@StartAutomating
Created October 17, 2024 05:35
Show Gist options
  • Save StartAutomating/5741990d133611d8aa88b65ef33f19f9 to your computer and use it in GitHub Desktop.
Save StartAutomating/5741990d133611d8aa88b65ef33f19f9 to your computer and use it in GitHub Desktop.
Gist a quick history ArgumentCompleter
# A function without a [CmdletBinding] attribute or [Parameter] attributes is freeform.
# Let's declare a little function that just outputs the name and arguments
function I {
param()
@($MyInvocation.InvocationName) + $args
}
# We can use Register-ArgumentCompleter to register the completer for a named command.
# This simple completer will show any matching history items
Register-ArgumentCompleter -CommandName I -ScriptBlock {
param($wordToComplete, $commandAst, $cursorPosition)
# Whenever we find a match, we need all elements except the one being completed
$upTilNow = foreach ($element in $commandAst.CommandElements) {
if ($element.Extent.EndOffset -ge $cursorPosition) {
break
}
$element
}
# Now, to find any matching history entries, we Get-History
foreach ($historyItem in Get-History) {
# looking for things that are _like_ the entire ast
if ($historyItem.CommandLine -like "$commandAst*") {
# and returning the current word(s) to complete
# replacing any leading whitespaces, so we don't tab too much.
$historyItem.CommandLine.Substring("$upTilNow".Length) -replace '^\s+'
}
}
}
# Give it a try
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment