Claudius
Claudius

Reputation: 156

Is there a way to make a Powershell function ignore a default parameter's value if its parameter set is not in use?

I understand from this answer that when you have default parameters and multiple parameter sets in a Powershell function, the default parameter values will be instantiated even if the parameter set in use is not the one in which they are inserted. Is there a way to avoid this?

For example, in the function below, assuming that there is a really expensive calculation used to compute the default value of $FirstParameter, I would like to avoid using it when it is not necessary:

function PrintStuff {
    [CmdletBinding(DefaultParameterSetName='FirstSet')]
    Param(
        [Parameter(ParameterSetName='FirstSet')]
        [String]$FirstParameter=(ReallyExpensiveFunction),

        [Parameter(ParameterSetName='SecondSet')]
        [String]$SecondParameter
    )

    if (-not ($FirstParameter -eq $null)) {Write-Host $FirstParameter}
    Write-Host "$($PSCmdlet.ParameterSetName)"
}

function ReallyExpensiveFunction {
    # Very expensive calculation
    "I Am First"
}

However, at the moment running it would still give me the results below:

PS C:\> PrintStuff
# I Am First
# FirstSet

PS C:\> PrintStuff -SecondParameter "don't print this"
# I Am First
# SecondSet

As per above, when SecondSet is used $FirstParameter is still being defined. Is there a way to get only SecondSet printed when the second parameter set is used?

Bear in mind, I am looking to find out if there is a solution which would allow me to keep ReallyExpensiveFunction as the default value for $FirstParameter, and avoid solutions which would involve transferring the logic to the body of the function, such as:

...
    Param(
        [Parameter(ParameterSetName='FirstSet')]
        [String]$FirstParameter,
    ...
    )

    if ($PSCmdlet.ParameterSetName -eq 'FirstSet' -and ($FirstParameter -eq '')) {
        $FirstParameter = ReallyExpensiveFunction
    }
...

Sorry if the pitch is too specific, but I am curious to find out if this is possible.

Upvotes: 3

Views: 1796

Answers (1)

Adil Hindistan
Adil Hindistan

Reputation: 6635

Unfortunately, the answer is no. ParameterSet allows to present a simpler interface to user for complex argument sets by filtering out the non-relevant ones. However, PowerShell goes through each parameter, whether it is in the selected parameterset or not and assign the default value to the parameter, if you specify one. So, simply put in the context of your question, ParameterSet may be thought as just a filter for presentation.

Upvotes: 4

Related Questions