【问题标题】:Powershell one of two parameters are mandatoryPowershell 两个参数之一是必需的
【发布时间】:2020-07-14 00:52:49
【问题描述】:

我写了一个带有一些参数的 powershell 脚本,但我不知道如何获得类似的语法

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

script.ps1 [A|B] C E F

script.ps1 [A|B] C G

目标:

  • A 或 B 或两者都通过了
  • C 始终是强制性的
  • 如果没有传递其他参数,则使用第一个参数集 -> D 不是强制性的
  • 如果传递了 E,则 F 是强制性的,反之亦然(第二个参数集)
  • G 被传递(第三个参数集)

我的脚本是这样的

[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'

所以参数 C - G 看起来不错。但是我不知道A和B的条件怎么写。

你有什么想法吗?

【问题讨论】:

    标签: powershell parameters parameter-sets


    【解决方案1】:

    对 $A 和 $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'
    #>
    

    如果您不想为 A 和 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
    }
    

    【讨论】:

    • 嗯我认为有几个问题,因为如果我将这些 ParameterSets 用于 $A 和 $B 我就不能再使用 $D-$G 了。我也无法通过 $A 和 $B。但我的目标是必须至少使用其中一个调用脚本 -> 通过 $A 或通过 $B 或通过 $A 和 $B
    • 嗯好吧看起来像一个解决方法,我会试试这个。认为还有一种方法可以使用 Param-Block 来处理这个问题。感谢您的帮助
    猜你喜欢
    • 2016-07-17
    • 1970-01-01
    • 2021-12-18
    • 2012-06-24
    • 2020-05-23
    • 2021-08-01
    • 2014-08-15
    • 1970-01-01
    • 2015-11-09
    相关资源
    最近更新 更多