1

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?

Emperor XLII
  • 13,014
  • 11
  • 65
  • 75
user1748546
  • 97
  • 2
  • 11
  • I have never written a cmdlet in C# before, but when I write a function in Powershell with a `[ValidateSet()]` attribute, it automatically tab completes the values for that parameter. – briantist Nov 26 '14 at 23:44

2 Answers2

1

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)]
Keith Hill
  • 194,368
  • 42
  • 353
  • 369
  • It did not work for me. Do I nned to specify any other attribute or add any configuration file ?? – user1748546 Nov 30 '14 at 00:27
  • I mean, How do you specify StringEncodingParameter ? That is the key. Is it a simple C# enum or you specify in a script or configuration file ? – user1748546 Nov 30 '14 at 00:35
  • 1
    You can see the implementation here https://pscx.codeplex.com/SourceControl/latest#Trunk/Src/Pscx.Core/StringEncodingParameter.cs That impl is a bit complex. I think you could define a C# enum and use that as the parameter type and get the parameter validation check for free. – Keith Hill Nov 30 '14 at 00:50
1

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.

Stephen Connolly
  • 1,639
  • 10
  • 15