【问题标题】:Having a optional parameter that requires another parameter to be present有一个可选参数,需要另一个参数存在
【发布时间】:2012-06-23 06:54:52
【问题描述】:

很简单,我如何初始化我的 Powershell 脚本的 params 部分,这样我就可以拥有类似的命令行参数

Get-Foo [-foo1] <foo1Arg> [-foo2 <foo2Arg> [-bar <barArg>]]

所以我唯一可以使用-bar 的时间是foo2 已定义。

如果 -bar 不依赖于 -foo2 我可以这样做

[CmdletBinding()]
param (
    [Parameter(Mandatory=$true)]
    [string]$foo1,

    [string]$foo2,

    [string]$bar
)

但是我不知道如何制作该依赖参数。

【问题讨论】:

标签: powershell powershell-2.0


【解决方案1】:

我对原始问题的阅读与 C.B. 的略有不同。来自

Get-Foo [-foo1] <foo1Arg> [-foo2 <foo2Arg> [-bar <barArg>]]

第一个参数 $foo1 始终是强制性的,而如果指定了 $bar,则也必须指定 $foo2。

所以我的编码是将 $foo1 放在两个参数集中。

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" 

当你运行上面的代码时,你会得到以下输出。

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

【讨论】:

    【解决方案2】:

    您需要 ParameterSet,阅读此处了解更多信息:

    http://msdn.microsoft.com/en-us/library/windows/desktop/dd878348(v=vs.85).aspx

    http://blogs.technet.com/b/heyscriptingguy/archive/2011/06/30/use-parameter-sets-to-simplify-powershell-commands.aspx

    您的代码示例:

    [CmdletBinding(DefaultParameterSetName="set1")]
    param (
        [Parameter(ParameterSetName="set1", Mandatory=$true)]
        [string]$foo1,
        [Parameter(ParameterSetName="set2",  Mandatory=$true)]
        [string]$foo2,
        [Parameter(ParameterSetName="set2")]
        [string]$bar
    )
    

    【讨论】:

    • 这正确地需要指定-foo2 以指定-bar,但是它不允许您在-foo1 之外指定-foo2,因为它们位于不同的参数集中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-16
    • 2010-10-23
    • 1970-01-01
    • 1970-01-01
    • 2018-10-21
    • 1970-01-01
    相关资源
    最近更新 更多