有一个需要另一个参数存在的可选参数 [英] Having a optional parameter that requires another parameter to be present
问题描述
很简单,我如何初始化我的 Powershell 脚本的 params
部分,以便我可以有一个像
Quite simply, how do I initialize the params
part of my Powershell Script so I can have a command line arguments like
Get-Foo [-foo1] <foo1Arg> [-foo2 <foo2Arg> [-bar <barArg>]]
所以我唯一可以使用 -bar
的时候是 foo2
已经被定义.
So the only time I can use -bar
is when foo2
has ben defined.
如果 -bar
不依赖于 -foo2
我可以这样做
If -bar
was not dependent on -foo2
I could just do
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[string]$foo1,
[string]$foo2,
[string]$bar
)
但是我不知道如何制作该依赖参数.
However I do not know what to do to make that dependent parameter.
推荐答案
我对原始问题的解读与 C.B. 的略有不同.来自
My reading of the original question is slightly different to C.B.'s. From
Get-Foo [-foo1] <foo1Arg> [-foo2 <foo2Arg> [-bar <barArg>]]
第一个参数 $foo1 始终是必需的,而如果指定了 $bar,则也必须指定 $foo2.
The first argument $foo1 is always mandatory, while if $bar is specified $foo2 must be specified too.
所以我的编码是将 $foo1 放在两个参数集中.
So my coding of it would be to put $foo1 in both parameter sets.
function Get-Foo
{
[CmdletBinding(DefaultParameterSetName="set1")]
param (
[Parameter(ParameterSetName="set1", Mandatory=$true, Position=0)]
[Parameter(ParameterSetName="set2", Mandatory=$true, Position=0) ]
[string]$foo1,
[Parameter(ParameterSetName="set2", Mandatory=$true)]
[string]$foo2,
[Parameter(ParameterSetName="set2", Mandatory=$false)]
[string]$bar
)
switch ($PSCmdlet.ParameterSetName)
{
"set1"
{
$Output= "Foo is $foo1"
}
"set2"
{
if ($bar) { $Output= "Foo is $foo1, Foo2 is $foo2. Bar is $Bar" }
else { $Output= "Foo is $foo1, Foo2 is $foo2"}
}
}
Write-Host $Output
}
Get-Foo -foo1 "Hello"
Get-Foo "Hello with no argument switch"
Get-Foo "Hello" -foo2 "There is no bar here"
Get-Foo "Hello" -foo2 "There" -bar "Three"
Write-Host "This Stops for input as foo2 is not specified"
Get-Foo -foo1 "Hello" -bar "No foo2"
当你运行上面的代码时,你会得到以下输出.
You then get the following output when you run the above.
Foo is Hello
Foo is Hello with no argument switch
Foo is Hello, Foo2 is There is no bar here
Foo is Hello, Foo2 is There. Bar is Three
This Stops for input as foo2 is not specified
cmdlet Get-Foo at command pipeline position 1
Supply values for the following parameters:
foo2: Typedfoo2
Foo is Hello, Foo2 is Typedfoo2. Bar is No foo2
这篇关于有一个需要另一个参数存在的可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!