简体   繁体   中英

Powershell C# cmdlet with parametersets with same subset of parameters

I have defined the following parameter sets in MyCustomCmdlet with default parameterset as two :

    [Parameter(Mandatory = true, ParameterSetName = one)]
    [Parameter(Mandatory = true, ParameterSetName = two)]
    [Parameter(Mandatory = true, ParameterSetName = three)]
    [Parameter(Mandatory = true, ParameterSetName = four)]
    [ValidateNotNullOrEmpty]
    [Alias("a")]
    public string A { get; set; }

    [Parameter(Mandatory = true, ParameterSetName = two)]
    [ValidateNotNullOrEmpty]
    [Alias("b")]
    public string B { get; set; }

    [Parameter(Mandatory = true, ParameterSetName = three)]
    [SupportsWildcards]
    [ValidateNotNullOrEmpty]
    [Alias("c")]
    public string C { get; set; }


    [Parameter(Mandatory = true, ParameterSetName = four)]
    [ValidateNotNullOrEmpty]
    [Alias("d")]
    public string D { get; set; }


    [Parameter]
    [ValidateNotNullOrEmpty]       
    public string E{ get; set; }

    [Parameter]
    [ValidateNotNullOrEmpty]
    public string F { get; set; }

During debug, am getting expected number of parameter sets ie 4 with following parameters:

1.ParameterSetName: one Parameters: A , E, F

2.ParameterSetName: two Parameters: A, B , E, F

3.ParameterSetName: three Parameters: A, C , E, F

4.ParameterSetName: four Parameters: A, D , E, F

However, when I execute:

MyCustomCmdlet -A or MyCustomCmdlet -A -E -F

I am getting error stating, requires mandatory parameter B which is part of default parameter set.

  1. Can someone please help me understand this behavior?
  2. How to execute the cmdlet using parameter set "one"

PowerShell will try and resolve the ParameterSet based off the command given and will not try and resolve a non default ParameterSet unless there the default is not resolvable with the current inputs. In your scenario ParameterSet 'two' is default and Parameter A is part of that ParameterSet, so logically that's what PowerShell assumes you're targeting as the input is still valid for it. If you want the ability to provide Parameter A on it's own you need to create a ParameterSet with just Parameter A included, and this has to be default (ParameterSet 'one' in your example).

E and F do not have their ParameterSet property defined, so by default their ParameterSet is set to ParameterSet.AllParameterSets , so again including these two fields is valid for the default set, so PowerShell still assumes that's what you're trying to do.

Also PowerShell is case-insensitive, so you don't need to Alias your parameters with the lower-case equivalent (if that is a representative scenario)

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