2

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?

Citu
  • 21
  • 5

1 Answers1

1

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
}
Wasif
  • 14,755
  • 3
  • 14
  • 34
  • Hmm I think there are several problems because if I use these ParameterSets for $A and $B I can't use $D-$G anymore. Also I have no possibility to pass $A and $B. But my target is that the script has to be called at least with one of them -> pass $A or pass $B or pass $A and $B – Citu Apr 02 '20 at 07:12
  • Hmm okay looks like a workaround and I will try this. Thought there is also a way to handle this with the Param-Block. Thank you for your help – Citu Apr 02 '20 at 10:29