Scott Chamberlain
Scott Chamberlain

Reputation: 127603

Having a optional parameter that requires another parameter to be present

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>]]

So the only time I can use -bar is when foo2 has ben defined.

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.

Upvotes: 11

Views: 15068

Answers (2)

Ian Jespersen
Ian Jespersen

Reputation: 191

My reading of the original question is slightly different to C.B.'s. From

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

The first argument $foo1 is always mandatory, while if $bar is specified $foo2 must be specified too.

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

Upvotes: 12

CB.
CB.

Reputation: 60976

You need ParameterSet, read here to know more about it:

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

Your code sample:

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

Upvotes: 7

Related Questions