Tab-Completion for ValidateSet for Powershell Cmdlet

1k Views Asked by At

I am using C# to create PowerShell cmdlets. For one of the parameters, I am using ValidateSet.

[ValidateNotNullOrEmpty]
[ValidateSet(new string[]{"STANDARD", "CUSTOM","MINIMUM","DEFAULT"},IgnoreCase=true)]
[Parameter(
    Mandatory = true,
    ValueFromPipelineByPropertyName = false,
    ValueFromPipeline = false,
    HelpMessage = "House Mode")
]
[Alias("hm")]
public string HouseMode
{
    get { return m_housemode; }
    set { m_housemode = value;  }
}   

How can I make the value of the ValidateSet appear in the tab-completion list?

2

There are 2 best solutions below

0
On

To avoid duplication you can also encode the valid values in an enum as follows. This is how I did it in PowerShell directly, but presumably declaring an enum in your c# code would work the same e.g.:

Add-Type -TypeDefinition @"
    public enum ContourBranch
    {
       Main,
       Planned,
       POP,
       Statements
    }
"@

Then declare your parameter as of that new type, viz

[CmdletBinding(SupportsShouldProcess=$True)]
param (
    [Parameter(Mandatory=$true)]
    [ContourBranch] $Branch 
)

This gives you tab completion and if you get the value wrong the error message also lists the valid enum values, which is pretty neat.

3
On

This is from the Format-Hex command in PSCX:

[Parameter(ParameterSetName = ParameterSetObject,
           ValueFromPipelineByPropertyName = true,
           HelpMessage = "The encoding to use for string InputObjects.  Valid values are: ASCII, UTF7, UTF8, UTF32, Unicode, BigEndianUnicode and Default.")]
[ValidateNotNullOrEmpty]
[ValidateSet("ascii", "utf7", "utf8", "utf32", "unicode", "bigendianunicode", "default")]
public StringEncodingParameter StringEncoding
{
    get { return _encoding; }
    set { _encoding = value; }
}

Tab completion works on this parameter. In your case, I think you want to specify the attribute like this:

[ValidateSet("STANDARD", "CUSTOM","MINIMUM","DEFAULT", IgnoreCase = true)]