如何在PowerShell中定义多组互斥参数?

时间:2019-03-13 19:04:29

标签: powershell parameters

如果存在多个(互斥参数)组,是否可以让PowerShell强制执行互斥参数?

例如,请考虑脚本Test.ps1中的这些参数(所有参数都是可选的,并且是非定位的):

Param(
    # GROUP A (a1 and a2 are mutually exclusive)
    [switch]$a1,
    [switch]$a2,

    # GROUP B (b1 and b2 are mutually exclusive)
    [switch]$b1,
    [switch]$b2
)

是否有一种方法可以强制执行A​​组中最多一个参数(即$a1$a2)和/或B组中最多一个参数(即$b1或{是{1}})?

以下呼叫将有效

$b2

以下呼叫将无效

.\Test.ps1
.\Test.ps1 -a1
.\Test.ps1 -a2
.\Test.ps1 -b1
.\Test.ps1 -b2
.\Test.ps1 -a1 -b1
.\Test.ps1 -a1 -b2
.\Test.ps1 -a2 -b1
.\Test.ps1 -a2 -b2

我知道如何使用.\Test.ps1 -a1 -a2 -b1 -b2 .\Test.ps1 -a1 -b1 -b2 .\Test.ps1 -a2 -b1 -b2 .\Test.ps1 -a1 -a2 -b1 .\Test.ps1 -a1 -a2 -b2 来强制执行一组互斥参数,但是我无法弄清楚如何执行多个组。甚至不确定是否有可能。请注意,实际示例比上面的示例更复杂(每个组具有多个参数,并且它们都不都是开关)。

更新:根据评论中的建议,我添加了参数集:

ParameterSetName

这似乎并没有满足我的要求:

PS D:\Scripts> Get-Help .\Test.ps1
Test.ps1 [-a1] [-a2] [-b2] [<CommonParameters>]
Test.ps1 [-a1] [-a2] [-b1] [<CommonParameters>]
Test.ps1 [-a1] [-b1] [-b2] [<CommonParameters>]
Test.ps1 [-a2] [-b1] [-b2] [<CommonParameters>]

1 个答案:

答案 0 :(得分:4)

您可以通过设置“必选”来解析“ ParameterSet”

function paramtest
{
    <# .Synopsis #>
    [CmdletBinding(DefaultParameterSetName = "default")]
    Param(
        # GROUP A (a1 and a2 are mutually exclusive)
        [Parameter(ParameterSetName="a1")]
        [Parameter(Mandatory, ParameterSetName="a1b1")]
        [Parameter(Mandatory, ParameterSetName="a1b2")]
        [switch]$a1,

        [Parameter(ParameterSetName="a2")]
        [Parameter(Mandatory, ParameterSetName="a2b1")]
        [Parameter(Mandatory, ParameterSetName="a2b2")]
        [switch]$a2,

        # GROUP B (b1 and b2 are mutually exclusive)
        [Parameter(ParameterSetName="b1")]
        [Parameter(Mandatory, ParameterSetName="a1b1")]
        [Parameter(Mandatory, ParameterSetName="a2b1")]
        [switch]$b1,

        [Parameter(ParameterSetName="b2")]
        [Parameter(Mandatory, ParameterSetName="a1b2")]
        [Parameter(Mandatory, ParameterSetName="a2b2")]
        [switch]$b2
    )

    "ParameterSetName is {0}" -f $PSCmdlet.ParameterSetName
}

Get-Help的结果如下。

PS > help paramtest | foreach syntax

paramtest [<CommonParameters>]

paramtest -a1 -b2 [<CommonParameters>]

paramtest -a1 -b1 [<CommonParameters>]

paramtest [-a1] [<CommonParameters>]

paramtest -a2 -b2 [<CommonParameters>]

paramtest -a2 -b1 [<CommonParameters>]

paramtest [-a2] [<CommonParameters>]

paramtest [-b1] [<CommonParameters>]

paramtest [-b2] [<CommonParameters>]
相关问题