1

我试图使一个参数成为强制性参数,但前提是另一个参数使用某些 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"))'"
    }
}
4

1 回答 1

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"))'"
    }
}

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

如果给出了TypeName参数,那么我可以做到,那么它们都是必需的。无论函数中的其他参数如何,这种情况都可能发生,例如上面的兄弟Number参数。

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

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

于 2018-04-10T15:24:32.823 回答