Adding argument completion to your PowerShell function parameters can improve the usability of your functions tremendously. A common approach is adding the [ValidateSet()] attribute to your parameter:

function Get-Country
{
  param
  (
    # suggest country names
    [ValidateSet('USA','Germany','Norway','Sweden','Austria','YouNameIt')]
    [string]
    $Name
  )

  # return parameter
  $PSBoundParameters
} 

When a user uses the Get-Country command and submits the -Name parameter, the function now suggests country names when the user presses TAB. Sophisticated PowerShell editors like PowerShell ISE or Visual Studio Code even open IntelliSense menus automatically or when you press CTRL+SPACE and show all values.

However, the [ValidateSet()] attribute limits the user to the listed values. No other values can be entered. If you wanted to suggest only the most commonly used server names for the -ComputerName parameter, the user would be restricted to these server names only. Not a good idea.

Beginning in PowerShell 7, there is a new attribute called [ArgumentCompletions()] which works almost like [ValidateSet()], except it skips the validation part. It provides the same argument completion but does not limit user input:

function Get-Country
{
  param
  (
    # suggest country names
    [ArgumentCompletions('USA','Germany','Norway','Sweden','Austria','YouNameIt')]
    [string]
    $Name
  )

  # return parameter
  $PSBoundParameters
}

This version of Get-Country suggests country names but you can still enter any other country name if you like.

Important: Due to a bug in PowerShell, argument completion will not work for the script pane in which the actual function is defined. Argument completion works fine in the PowerShell console and any other editor script pane.

The new [ArgumentCompletions()] attribute is missing in Windows PowerShell, so when you use it, your function is no longer compatible to Windows PowerShell. We’ll work around this issue in our upcoming tip.


Twitter This Tip! ReTweet this Tip!

Anonymous