35

I've been trying to search for an answer, but I think that having the words PowerShell and parameter together in a set of keywords are not making for an easy search

My question is, I'm writing a function, and I've supplied a parameter, but the parameter has to be one of a list of specific strings.

Is there a way I can supply these strings within the script so that if I type "myfunction -parameter .." I can use tab completion for the parameter value?

2 Answers 2

61

If you are on PowerShell V2 you can use the [ValidateSet()] attribute e.g.:

param(
    [Parameter()]
    [ValidateSet('foo','bar','baz')]
    [string[]]
    $Item
)

See the help topic by executing:

man about_functions_advanced_parameters
Sign up to request clarification or add additional context in comments.

Comments

4

You can use [ValidateSet()] as Keith demonstates, but this doesn't work very well with a large number of possible values (populating the list when you hit Tab becomes very slow). Another method for getting tab completion is to make a custom enum:

https://devblogs.microsoft.com/powershell/v2-custom-enums/

and cast the parameter as that enum type. This does impose some limitations on the character set that's allowed in your strings (basically just letters and number), but it will populate the tab completion list much faster if it's a relatively large list of values.

1 Comment

Do you have a code example for inside a script? Not sure how it'd work exactly.

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.