PowerShell function arguments: Can the first one be optional first?
        Posted  
        
            by Johannes Rössel
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Johannes Rössel
        
        
        
        Published on 2010-05-31T08:18:19Z
        Indexed on 
            2010/05/31
            8:22 UTC
        
        
        Read the original article
        Hit count: 296
        
powershell
|parameters
I have an advanced function in PowerShell, which roughly looks like this:
function Foo {
    [CmdletBinding]
    param (
        [int] $a = 42,
        [int] $b
    )
}
The idea is that it can be run with either two, one or no arguments. However, the first argument to become optional is the first one. So the following scenarios are possible to run the function:
Foo a b    # the normal case, both a and b are defined
Foo b      # a is omitted
Foo        # both a and b are omitted
However, normally PowerShell tries to fit the single argument into a. So I thought about specifying the argument positions explicitly, where a would have position 0 and b position 1. However, to allow for only b specified I tried putting a into a parameter set. But then b would need a different position depending on the currently-used parameter set.
Any ideas how to solve this properly? I'd like to retain the parameter names (which aren't a and b actually), so using $args is probably a last resort. I probably could define two parameter sets, one with two mandatory parameters and one with a single optional one, but I guess the parameter names have to be different in that case, then, right?
© Stack Overflow or respective owner