我想定义三个参数集
我该怎么做?
这就是我当前的代码。
[Parameter(ParameterSetName = ParameterSet1, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The ResourceGroupName")]
[Parameter(ParameterSetName = ParameterSet2, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The ResourceGroupName")]
[Parameter(ParameterSetName = ParameterSet3, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The ResourceGroupName")]
public String ResourceGroupName { get; set; }
[Parameter(ParameterSetName = ParameterSet2, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The name of metric alert rule")]
[Parameter(ParameterSetName = ParameterSet3, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The ResourceGroupName")]
public String Name { get; set; }
答案 0 :(得分:0)
我想定义三个参数集
cmdletName -param1
(ParameterSet1)cmdletName -param1 -param2
(ParameterSet2)cmdletName
(此参数没有任何参数)(ParameterSet3)我该怎么做?
以下是带有一些调试输出的注释 Powershell解决方案:
function cmdletName{
param(
[parameter( Mandatory=$true, ParameterSetName="ParameterSet1",
ValueFromPipelineByPropertyName=$true)]
[parameter( Mandatory=$true, ParameterSetName="ParameterSet2",
ValueFromPipelineByPropertyName=$true)]
### [ValidateNotNullOrEmpty()]
[string]$param1,
[parameter( Mandatory=$true, ParameterSetName="ParameterSet2",
ValueFromPipelineByPropertyName=$true)]
### [ValidateNotNullOrEmpty()]
[string]$param2,
[parameter( Mandatory=$false, ParameterSetName="ParameterSet3",
DontShow, HelpMessage="dummy parameter")]
[string]$AnythingFake='?'
)
process {
Write-Host $PsCmdlet.ParameterSetName -ForegroundColor Yellow
# The following `switch` statement calls a different method
# based on which parameter set the user has specified.
switch ($PsCmdlet.ParameterSetName)
{
"ParameterSet1" { "$param1/*/*"; break}
"ParameterSet2" { "$param1/$param2/*"; break}
"ParameterSet3" { "*/*/$AnythingFake"; break}
Default { throw "impossible"; break}
}
}}
可能的用法示例
# Prepare parameters for pipeline
$par1 = [PSCustomObject]@{param1='p1p'}
$par12 = [PSCustomObject]@{param1='P1P';param2='p2p'}
# Possible valid call # ParameterSetName
cmdletName -param1 "p1" # ParameterSet1
cmdletName -param1 "P1" -param2 "p2" # ParameterSet2
cmdletName # ParameterSet3
$par1 | cmdletName # ParameterSet1
$par12 | cmdletName # ParameterSet2
结果:
ParameterSet1
p1/*/*
ParameterSet2
P1/p2/*
ParameterSet3
*/*/?
ParameterSet1
p1p/*/*
ParameterSet2
P1P/p2p/*