Home > other >  For a cmdlet parameter provide a list of common options, but still let them enter anything they want
For a cmdlet parameter provide a list of common options, but still let them enter anything they want

Time:01-23

Using ValidateSet for a parameter on a cmdlet, will give a list of possible parameters. But will not let the user of that cmdlet enter other values. Example the below

[ValidateSet('A','B')

Would let the users enter A or B, but nothing else.

I would like to provide a list that give the most common option, but also allow them to enter anything else.

For example, a parameter that takes a path to a build. Build A and B are shipped and stable builds. But there are many other builds. So, I want to provide a list of A and B build so they do not need to know the path to them but then also let them enter any other path to any other build.

Is this possible?

CodePudding user response:

Use an ArgumentCompleter attribute, which specifies what values should be offered via tab-completion, while not limiting what values may be passed (by entering them manually / pasting them); e.g.:

function Get-Foo {
  param(
    # Suggest 'A' and 'B' as tab-completions, but allow any
    # other value to be passed as well.
    [ArgumentCompleter({ 
      param($cmd, $param, $wordToComplete) 
      'A', 'B' -like "$wordToComplete*" 
    })]
    [string] $MyParam
  )
 
  "[$MyParam]" # sample output
}

Typing Get-Foo <tab> then offers A and B as completions, while still allowing any other value to be passed too.

With single-character completion values such as A and B it isn't obvious, but the solution above allows you type a prefix of the completion values to narrow down the completions.

  • Related