Powershell C# commandlets Conditional switch parameters

948 views Asked by At

I need to apply conditional switch parameter only if other parameter is provided. Can any body let me know how can I achieve this in C#

I want following way command let accessible on powershell terminal.

Edit

 Get-Parameter # this will process other path of the code and won't throw an error. (e.g. Not providing name of parameter, it would return all parameters in the container )

Get-Parameter -Name "Epics" -Writeable # writeable is switch parameter
Get-Parameter -Writeable # should throw an error ( Writeable switch only allows when Name parameter is provided.

Following is C# commandlet code.

[Cmdlet(VerbsCommon.Get, "Parameter")]
public class GetParameter : PSCmdlet
{
    [Parameter(
        Position = 1,
        Mandatory = false,
        ValueFromPipeline = true,
        ValueFromPipelineByPropertyName = true, ParameterSetName = "Name")
    ]
    public string Name { get; set; }

    [Parameter(Mandatory = true, ParameterSetName = "Name" ,ValueFromPipeline = true,
    ValueFromPipelineByPropertyName = true)]
    public SwitchParameter Writeable { get; set; } = false;
}
1

There are 1 answers

3
Tudor On

Based on the comments I think you need something like this:

[Cmdlet(VerbsCommon.Get, "Parameter")]
public class GetParameter : PSCmdlet
{
    [Parameter(
        Position = 0,
        Mandatory = true,
        ValueFromPipeline = true,
        ValueFromPipelineByPropertyName = true,
        ParameterSetName = "Name")
    ]
    public string Name { get; set; }

    [Parameter(
        Mandatory = false,
        ParameterSetName = "Name",
        ValueFromPipeline = true,
        Position = 1,
        ValueFromPipelineByPropertyName = true)]
    public SwitchParameter Writeable { get; set; } = false;
}