简体   繁体   中英

Tab-Completion for ValidateSet for Powershell Cmdlet

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?

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)]

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 eg:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM