您可以将Subject设为可选并在脚本主体的开头处理要求,模拟强制参数,如下所示:
param(
[parameter(Mandatory=$true)][ValidateSet("Add","Delete")] [string]$Command,
[string] $Subject
)
if (($Command -eq 'Add') -and ($PSBoundParameters['Subject'] -eq $null)) {
$Subject = Read-Host 'Supply value for the parameter "Subject" (mandatory when the value of "Command" is "Add")'
}
如果未指定参数主题,则条件$PSBoundParameters['Subject'] -eq $null
评估为 True 。请注意,您不能简单地使用,因为如果省略参数, $Subject将被初始化为空字符串。如果您不进行类型转换$Subject(即,省略 ),那么如果省略它,它将为 null,但我认为您不想这样做。$Subject -eq $null
[string]
请注意,这将允许用户在出现提示时简单地点击 [ENTER],将$Subject留空,但这是强制参数的标准行为。如果您不想允许这样做,您可以执行以下操作之一(这是在主体中而不是在参数声明中处理此类复杂参数要求的另一个优点)。
抛出错误:
param(
[parameter(Mandatory=$true)][ValidateSet("Add","Delete")] [string]$Command,
[string] $Subject
)
if (($Command -eq 'Add') -and ($PSBoundParameters['Subject'] -eq $null)) {
$Subject = Read-Host 'Supply value for the parameter "Subject" (mandatory when the value of "Command" is "Add"'
if (-not $Subject) {
throw "The Subject may not be blank."
}
}
一直提示直到提供值:
param(
[parameter(Mandatory=$true)][ValidateSet("Add","Delete")] [string]$Command,
[string] $Subject
)
if (($Command -eq 'Add') -and ($PSBoundParameters['Subject'] -eq $null)) {
do {
$Subject = Read-Host 'Supply value for the parameter "Subject" (mandatory when the value of "Command" is "Add"'
if (-not $Subject) {
Write-Host -NoNewline "The Subject may not be blank. "
}
} until ($Subject)
}