powershelltab-completion

How to get a parameter for my function to auto complete Command names like 'Get-Command'?


I am writting a function that will b providing help for the various commands/functions I have. I know PowerShell already goes to a great length with "real time" help, I just need a function or two in this vain for my niche purposes.

Get-Command can somehow suggest commands/functions that are part of the session as well as "unloaded" ones, I would like the 'Name' parameter of my function to also do this but I am at a loss here, I searched around and have turned up with nothing usefull.

What I have in mind is something like the following, where pressing tab at 'Name' parameter, suggest command names:

Function Get-Help{
    Param(
    $Name 
    )

    #Do something with the provided command/function name
}

PWSH 7.4


Solution

  • Use the built-in type CompletionCompleters:

    Register-ArgumentCompleter -CommandName Get-Help -ParameterName Name -ScriptBlock {
        param(
            [string] $commandName,
            [string] $parameterName,
            [string] $wordToComplete,
            [System.Management.Automation.Language.CommandAst] $commandAst,
            [System.Collections.IDictionary] $fakeBoundParameters
        )
    
        [System.Management.Automation.CompletionCompleters]::CompleteCommand(
            $wordToComplete)
    }
    

    If you want to limit the completions to only cmdlets or cmdlets and functions you can use the CompleteCommand(String, String, CommandTypes) overload:

    Register-ArgumentCompleter -CommandName Get-Help -ParameterName Name -ScriptBlock {
        param(
            [string] $commandName,
            [string] $parameterName,
            [string] $wordToComplete,
            [System.Management.Automation.Language.CommandAst] $commandAst,
            [System.Collections.IDictionary] $fakeBoundParameters
        )
    
        [System.Management.Automation.CompletionCompleters]::CompleteCommand(
            $wordToComplete,
            $null, # <- moduleName argument. $null = all modules. Supports wildcards.
            [System.Management.Automation.CommandTypes] 'Cmdlet, Function')
    }