Question

Consider this Cmdlet (usings removed):

public class Foo : Cmdlet
{
    [Parameter(Mandatory = true, ParameterSetName = "Foo"]
    public string A { get; set; }

    [Parameter(Mandatory = true, ParameterSetName = "Bar"]
    public string B { get; set; }

    [Parameter(Mandatory = true, ParameterSetName = "Bar"]
    public string C { get; set; }

    protected override void ProcessRecord()
    {
         /* magic goes here */
    }
}

Now the way you can execute this Cmdlet is as follows:

# like this
Foo

# or
Foo -A "test"

# or
Foo -B "test" -C "test"

Having and A and B doesn't work, neither does only using B (requires C).

So that's fine, however I want to prevent that you can execute the Cmdlet by just typing Foo, now I can check that in code, but since Powershell is so awesome, is there a way to enforce this through the runtime?

Was it helpful?

Solution

You may instruct PowerShell to default to a named parameter set, by way of the DefaultParameterSetName property of the CmdletAttribute attribute:

[Cmdlet("Foo", "Bar", DefaultParameterSetName = "Foo")]
public class Foo : Cmdlet
{
   // ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top