PowerShell 中的条件强制
Conditional Mandatory in PowerShell
我正在尝试强制设置一个参数,但前提是另一个参数使用特定的 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"))'"
}
}
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"))'"
}
}
参数集似乎有助于模拟条件强制参数。
如果提供了 Type 或 Name 参数,那么它们都是必需的。无论函数中的其他参数如何,都会发生这种情况,例如上面的同级 Number 参数。
我将默认参数集名称设置为随机的;我通常指定 "None"。该参数集名称不需要实际存在,同样由 Number 参数指示。
无论您的严格模式设置如何,所有这些都有效。
我正在尝试强制设置一个参数,但前提是另一个参数使用特定的 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"))'"
}
}
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"))'"
}
}
参数集似乎有助于模拟条件强制参数。
如果提供了 Type 或 Name 参数,那么它们都是必需的。无论函数中的其他参数如何,都会发生这种情况,例如上面的同级 Number 参数。
我将默认参数集名称设置为随机的;我通常指定 "None"。该参数集名称不需要实际存在,同样由 Number 参数指示。
无论您的严格模式设置如何,所有这些都有效。