1

This has been posted once before, but the proposed solution didn't solve my problem. I'm writing a script, and I want one of my parameters to be mandatory, but I only want it to be mandatory if one of the earlier parameters has a certain value.

Example:

param([Parameter(Mandatory=$true, Position=0)]
  [ValidateSet("Add","Delete")]
  [string]$Command,

  [Parameter(Mandatory=$true)]
  [string]$Subject
)

I want the Subject parameter to be required only if the Command parameter has the value "Add".

I've tried using a ParameterSetName value, but that didn't seem to work.

4

2 回答 2

2

You could try doing your parameters like this:

param (
    [Parameter(ParameterSetName="Add")][switch]$Add,
    [Parameter(ParameterSetName="Delete")][switch]$Delete,
    [Parameter(ParameterSetName="Add",Mandatory=$true)] [Parameter(ParameterSetName="Delete")] [string]$Subject
)

When you have the switch "Add" then the Subject is mandatory, when you have the switch "Delete" then the Subject parameter is optional.

于 2013-06-27T20:19:09.597 回答
2

您可以将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)
}
于 2013-06-27T21:36:24.820 回答