更新。以下注释代码 sn-p 基于Add a parameter to multiple Parameter Sets 文章。允许同时提供-Class 或-School 参数或两者。
function Get-Students{
param(
[parameter(Mandatory=$false)][switch]$SomeThing, # any type instead of [switch]
# ↑↑↑ parameter(s) in all Parameter Sets
[parameter(Mandatory=$true, ParameterSetName="School No Null")]
[parameter(Mandatory=$true, ParameterSetName="Class And School")]
[ValidateNotNullOrEmpty()]
[string]$School,
[parameter(Mandatory=$true, ParameterSetName="Class No Null")]
[parameter(Mandatory=$true, ParameterSetName="Class And School")]
[ValidateNotNullOrEmpty()]
[string]$Class
)
Write-Host $PsCmdlet.ParameterSetName -ForegroundColor Cyan
switch ($PsCmdlet.ParameterSetName)
{
"School No Null" { "$School/*,$($SomeThing.IsPresent)"; break}
"Class No Null" { "*/$Class,$($SomeThing.IsPresent)"; break}
"Class And School" { "$School/$Class,$($SomeThing.IsPresent)"; break}
}
}
Get-Students -Class "A"
Get-Students -School "West" -SomeThing
Get-Students -Class "A" -School "West"
### errors raised:
# Get-Students
### Parameter set cannot be resolved using the specified named parameters.
### + FullyQualifiedErrorId : AmbiguousParameterSet,Get-Students
# Get-Students -Class ""
# Get-Students -School ""
### Cannot validate argument on parameter '…'. The argument is null or empty.
### + FullyQualifiedErrorId : ParameterArgumentValidationError,Get-Students
原始答案(代码 sn-p 基于 PowerShell 团队博客中的 PowerShell V2: ParameterSets 文章 和 MSDN help article)不允许 同时提供 both -Class 和 -School 参数:
function Get-Students{
param(
[parameter(Mandatory=$true, ParameterSetName="School No Null")][ValidateNotNullOrEmpty()]
[parameter(Mandatory=$false, ParameterSetName="Class No Null")] #[AllowNull()]
[string]$School,
[parameter(Mandatory=$true, ParameterSetName="Class No Null")] [ValidateNotNullOrEmpty()]
[parameter(Mandatory=$false, ParameterSetName="School No Null")]#[AllowNull()]
[string]$Class
)
Write-Host $PsCmdlet.ParameterSetName -ForegroundColor Cyan
switch ($PsCmdlet.ParameterSetName)
{
"School No Null" { $School; break}
"Class No Null" { $Class; break}
}
}
### valid calls:
Get-Students -Class "A"
Get-Students -School "West"
### errors raised:
### Parameter set cannot be resolved using the specified named parameters.
# Get-Students
# Get-Students -Class "A" -School "West"
### The argument is null or empty.
# Get-Students -Class ""
# Get-Students -School ""