Igal Tabachnik
Igal Tabachnik

Reputation: 31548

Custom PowerShell tab-completion for a specific command?

I was wondering if it's possible to create a custom tab completion in PowerShell, that would provide a specific list of arguments after a certain command?

When launching Visual Studio from a command line, you can type devenv /rootsuffix HiveName to have Visual Studio launch a new "hive" with that name, creating a folder called HiveName on the disk in a special location.

I want to be able to type in PowerShell: devenv /rootsuffix [tab], and get a list of existing hives (from looking up in a directory/registry, doesn't matter), overriding the default behavior, which is filename completion.

Is doing something like this possible?

Upvotes: 4

Views: 3068

Answers (1)

Dave F
Dave F

Reputation: 1985

This can be done using the Register-ArgumentCompleter command.

The following is an example of code that uses the command (which can be copied and pasted into your PowerShell window):

# Function that will be registered with the command
function Cmd {
    Param(
        [string] $Param
    )

    Write-Host "Param: $param"
} 

# The code that will perform the auto-completion
$scriptBlock = {
    # The parameters passed into the script block by the
    #  Register-ArgumentCompleter command
    param(
        $commandName, $parameterName, $wordToComplete,
        $commandAst, $fakeBoundParameters
    )

    # The list of values that the typed text is compared to
    $values = 'abc','adf','ghi'

    foreach ($val in $values) {
        # What has been typed matches the value from the list
        if ($val -like "$wordToComplete*") {
            # Print the value
            $val
        }
    }
}

# Register our function and auto-completion code with the command
Register-ArgumentCompleter -CommandName Cmd `
 -ParameterName Param -ScriptBlock $scriptBlock

We can check that this code works properly by typing the following incomplete commands into the shell and pressing the TAB key (where <PRESS TAB> is typed) in the prompt:

# Using autocomplete with the TAB key will produce the results: abc, adf
PS > Cmd -Param a<PRESS TAB>

# Using autocomplete with the TAB key will produce the results: abc
PS > Cmd -Param ab<PRESS TAB>

Upvotes: 7

Related Questions