10

簡単に言うとparams、Powershell スクリプトの一部を初期化して、次のようなコマンド ライン引数を指定するにはどうすればよいですか?

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

したがって、使用できるのは が定義されて-barいるときだけです。foo2

-barに依存していなければ、-foo2私はただできる

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

    [string]$foo2,

    [string]$bar
)

ただし、その依存パラメーターを作成するにはどうすればよいかわかりません。

4

2 に答える 2

11

元の質問の私の読み方は、CB のものとは少し異なります。から

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
于 2013-04-17T11:04:11.930 に答える
7

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
)
于 2012-06-21T05:01:50.190 に答える