Rakha
Rakha

Reputation: 2064

Powershell function - parameter has to be mandatory in one case, optional in another

I have this function :

function AlwaysRunAtLogon {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true)]
        [System.String]$NomTache,
        [Parameter(Mandatory = $true)]
        [System.String]$Script,
        [switch]$retrait

    )

...
}

Use case #1 is :

AlwaysRunAtLogon -NomTache AnyName C:\temp\script.ps1

Which will run code to ADD something. This is working fine. I now want to add a SWITCH parameter to my function so it can DELETE something based on the value of the first parameter (NomTache)

So use case #2 would be :

AlwaysRunAtLogon -NomTache AnyName -Retrait

Now here is the problem. In case #1, I want to keep $Script mandatory so the user HAS to supply a script file. However, in case #2, $Script is now optional since the delete operations only need the first parameter to work (NomTache)

How do I adapt this function so I can both use case 1 and 2 ? There is probably a logic problem somewhere. I'm new at functions so thanks for your help. I'm open to any redesign.

Am I just better off doing another function for example "RemoveAlwaysRunAtLogon" and run it like this ? :

RemoveAlwaysRunAtLogon -NomTache AnyName

Upvotes: 0

Views: 47

Answers (2)

Rakha
Rakha

Reputation: 2064

Got it working like this thanks to vrdse above :

function AlwaysRunAtLogon {

    [CmdletBinding()]

    param (

        [Parameter(ParameterSetName='Ajout',Mandatory=$true)]

        [Parameter(Position=0,ParameterSetName='Retrait',Mandatory=$true)]
        [System.String]$Nom,


        [Parameter(Position=1,ParameterSetName='Ajout',Mandatory = $true)]
        [System.String]$Script,

        [Parameter(ParameterSetName='Retrait')]

        [switch]$retrait

        )

    ....

}

Upvotes: 0

vrdse
vrdse

Reputation: 3154

You can solve your problem with ParameterSets.

Not sure if I understood your requirement entirely, so this is just an example. But I think the model is clear.

function AlwaysRunAtLogon {
    [CmdletBinding()]
    param (
        [Parameter(
            ParameterSetName='Name1',
            Mandatory=$true
        )]
        [Parameter(
            ParameterSetName='Name2',
            Mandatory=$true
        )]
        [System.String]$NomTache,
        [Parameter(
            ParameterSetName='Name1',
            Mandatory = $true
        )]
        [System.String]$Script,
        [Parameter(
            ParameterSetName='Name2'
        )]
        [switch]$retrait

    )

...
}

Upvotes: 2

Related Questions