PowerShell中的条件强制性

时间:2018-04-10 15:24:33

标签: powershell cmdlet parameter-sets validateset

我试图强制创建一个参数,但前提是另一个参数使用某些ValidateSet值。似乎在Mandatory上使用代码块并不像预期的那样工作。

function Test-Me {
    [CmdletBinding()]
    Param (
        [Parameter()]
        [ValidateSet("NameRequired", "AlsoRequired")]
        [string]
        $Type = "NoNameRequired",

        [Parameter(Mandatory = {-not ($Type -eq "NoNameRequired")})]
        [string]
        $Name
    )

    Process {
        Write-Host "I ran the process block."
        Write-Host "Type = '$Type'"
        Write-Host "Name = '$Name'"
        Write-Host "Name Parameter Mandatory? = '$(-not ($Type -eq "NoNameRequired"))'"
    }
}

1 个答案:

答案 0 :(得分:0)

Set-StrictMode -Version Latest

function Test-Me {
    [CmdletBinding(DefaultParameterSetName = "Gorgonzola")]
    Param (

        [Parameter(Mandatory)]
        [int]
        $Number,

        [Parameter(Mandatory, ParameterSetName = "NameNeeded")]
        [ValidateSet("NameRequired", "AlsoRequired")]
        [string]
        $Type = "NoNameRequired",

        [Parameter(Mandatory, ParameterSetName = "NameNeeded")]
        [string]
        $Name
    )

    Process {
        Write-Host "I ran the process block."
        Write-Host "Number = '$Number'"
        Write-Host "Type = '$Type'"
        Write-Host "Name = '$Name'"
        Write-Host "Name Parameter Mandatory = '$(-not ($Type -eq "NoNameRequired"))'"
    }
}

参数集似乎有助于模拟条件强制参数。

如果给出了类型名称参数,我可以将它设置到哪里,那么它们都是必需的。无论函数中的其他参数如何,都可能发生这种情况,例如上面的兄弟 Number 参数。

我将默认参数集名称设置为随机;我通常指定"无"。该参数集名称不需要实际存在,再次由Number参数指示。

无论您的严格模式设置如何,所有这些都有效。