1

It is possible in PowerShell to validate the parameters passed to a script and also enables auto completion, as seen below:

myscript.ps1:

param([Parameter(Mandatory=$false)][String][ValidateSet('abc',
                                                        'def',
                                                        'ghi')] $argument
     )

But this only enables the auto completion for the first argument. I want number of "auto complete"-able parameters to be arbitrary.

Therefore after typing:

  • PS C:\> .\myscript.ps1 def (additional white space at the end) and
  • pressing tab, I want the possible parameters to be auto completed again PS C:\> .\myscript.ps1 def abs

How do I code this in the param(...) part?

0

1 Answer 1

3

If you do want to pass values as individual arguments separated with whitespace, use the ValueFromRemainingArguments parameter attribute:

param(
  [Parameter(ValueFromRemainingArguments)]
  [ValidateSet('abc', 'def', 'ghi')]
  [string[]] $argument
 )

Note that $argument is now an array of values, in which PowerShell collects all positional arguments for you.

The potential down-side is that this subjects all positional arguments to the validation, so if you also need to pass other arguments, you'll have to prefix them with the parameter name (e.g., -foo bar).


Therefore, consider using a single, explicitly array-valued parameter instead:

param(
      [ValidateSet('abc', 'def', 'ghi')] 
      [string[]] $argument
     )

That way, $argument will receive multiple values if passed with , as the separator, and in addition to tab-completing the 1st value, each additional one after typing , can be tab-completed too.

./myscript a<tab>  # -> ./myscript abc

./myscript abc, d<tab<  # -> ./myscript abc, def
Sign up to request clarification or add additional context in comments.

1 Comment

My pleasure, @user69453; glad to hear it helped.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.