powershellvalidationparameter-passing

How to add additional values to 'ValidateSet' when using a class to dynamically get a list?


I have a function, I want to dynamically provide values for the Name parameter using a list of file names found in c:\names, so that tab always provides names that are UpToDate. I have figured out how to do this with a class but I want to do some "clever" handling as well. If the user provides * or ? as a value, then that should be acceptable as well. I want to essentially use these characters as "modifiers" for the parameter.

The following is what I have:

Function fooo{
    Param(
    [ValidateSet([validNames], "*", ErrorMessage = """{0}"" Is not a valid name")]
    #[ValidateSet([validNames], ErrorMessage = """{0}"" Is not a valid name")]           #'tab' works as expected here
    [string]$Name
    )
    if ($name -eq "*"){"Modifier Used, do something special insead of the usual thing"}
    $name
}

Class validNames : System.Management.Automation.IValidateSetValuesGenerator{
    [string[]] GetValidValues(){
        return [string[]] (Get-ChildItem -path 'C:\names' -File).BaseName
    }}

With the above tab does not auto complete any values for the Name parameter, and sometimes I will even get an error:

MetadataError: The variable cannot be validated because the value cleanup4 is not a valid value for the Name variable.

I can provide the value * to Name fine, I done get any errors:

fooo -name *

#Modifier Used, do something special insead of the usual thing

I know I can just use a switch parameter here, instead of going down this route, my main concern is how do I add additional values on top of the values provided by the ValidNames class? Something like:

...
[ValidateSet([validNames], "foo", "bar", "baz", ErrorMessage = """{0}"" Is not a valid name")]
...

I am on PWS 7.4


Solution

  • You can not combine passing an System.Management.Automation.IValidateSetValuesGenerator-implementing type with enumerating additional values literally in a [ValidateSet()] attribute.[1]


    [1] This constraint is implied by the only two constructors available for said attribute. With two or more arguments, the overload ValidateSetAttribute(String[]) is chosen, which assumes literally enumerated valid values; [ValidateSet([validNames], "*") therefore results in only two valid values: the stringified version of type [validvalues], i.e. [validvalues].ToString(), which yields 'validvalues', and '*'.