Argument-completers

Argument-completers have been around in a number of different forms since PowerShell 2. This section focuses on the implementation of argument-completers available in Windows PowerShell 5 and PowerShell Core.

An argument-completer is used by the tab completion system to provide a value for a parameter when Tab is pressed. For example, the Get-Module command cycles though module names when Tab is pressed after the command name. The argument-completer does not restrict the values that may be supplied; it is only used to offer values, to make the use of a command easier for an end user.

An argument-completer is a script block; the script block should accept the following parameters:

  • commandName
  • parameterName
  • wordToComplete
  • commandAst
  • fakeBoundParameter

Any of these parameters may be used, but the most important and the most frequently used is wordToComplete.

The following example would suggest words from a fixed list:

param ( $commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter )

$possibleValues = 'Start', 'Stop', 'Create', 'Delete'
$possibleValues | Where-Object { $_ -like "$wordToComplete*" }

Notice that a wildcard, *, has been added on the end of wordToComplete. Arguably, ValidateSet might be a better option in this case as it also feeds tab completion. However, where ValidateSet enforces, ArgumentCompleter suggests. The argument-completer only suggests when the user is using tab to complete a parameter value so it cannot replace ValidateSet or any other parameter validation steps. Unlike ValidateSet, and perhaps more like ValidateScript, the list of possible values used in an argument-completer can be dynamic. That is, the list of possible values can be the result of running another command. PowerShell provides two different ways to assign an argument completer: the ArgumentCompleter attribute or the Register-ArgumentCompleter command.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.128.199.88