Powershell one of two parameters are mandatory

3.2k views Asked by At

I wrote a powershell script with some parameters but I can't figured out how to get the syntax like

script.ps1 [A|B] C [D]

script.ps1 [A|B] C E F

script.ps1 [A|B] C G

Target:

  • A or B or both are passed
  • C is always mandatory
  • if no other parameter is passed use first parameterset -> D is not mandatory
  • if E is passed F is mandatory and vice versa (second parameterset)
  • G is passed (third parameterset)

My script looks like that

[CmdLetbinding(DefaultParameterSetName='ParamSet1')]
Param(
    [Parameter(Mandatory=$true)][String]$A,
    [Parameter(Mandatory=$false)][System.Net.IPAddress[]]$B,

    [Parameter(Mandatory=$true)][String]$C,

    [Parameter(Mandatory=$false, ParameterSetName="ParamSet1")][Int32]$D=120,

    [Parameter(Mandatory=$true, ParameterSetName="ParamSet2")][String]$E,
    [Parameter(Mandatory=$true, ParameterSetName="ParamSet2")][String]$F,

    [Parameter(Mandatory=$true, ParameterSetName="ParamSet3")][Switch]$G
)

Result of 'Get-Help script.ps1'

So parameter C - G looks fine. But I don't know how to write the condition for A and B.

Do you have any idea?

1

There are 1 answers

2
Wasif On

Use two parameter sets for $A and $B:

[CmdLetbinding(DefaultParameterSetName='ParamSet1')]
Param(
    [Parameter(Mandatory=$true,ParameterSetName='By_A')][String]$A,
    [Parameter(Mandatory=$true,ParameterSetName='By_B')][System.Net.IPAddress[]]$B,

# Rest of the Param
)
<#
 In the function's code, you can either test for whether $A and/or $B are null, or check $PSBoundParameters.ContainsKey('A'), or check $PSCmdlet.ParameterSetName to see whether it
is set to 'By_A' or 'By_B'
#>

If you don't want to use parameter sets for A and B:

Param(
# Param block, specifying both A and B mandatory=$false
)
If($A -ne $null){
  # A is not null, like this you can check if B is null. If B is not null then you can throw an exception
}
If($B -be $null){
    # B is not null, like this you can check if A is null. If A is not null then you can throw an exception
}