Reputation: 21
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:
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?
Upvotes: 2
Views: 3863
Reputation: 15518
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
}
Upvotes: 1