Mark Allison
Mark Allison

Reputation: 7228

How to use a default value with parameter sets in PowerShell?

I have this function

Function Do-ThisOrThat
{
[cmdletbinding()]
param (
    [Parameter(Mandatory = $false, ParameterSetName="First")]
    [string]$FirstParam = "MyFirstParam",

    [Parameter(Mandatory = $false, ParameterSetName="Second")]
    [string]$SecondParam
    )
    Write-Output "Firstparam: $FirstParam. SecondParam $SecondParam"
}

If I call the function like this Do-ThisOrThat I want it to detect that the $FirstParam has a default value and use that. Is it possible? Running it as is only works if I specify a parameter.

e.g. this works: Do-ThisOrThat -FirstParam "Hello"

Upvotes: 4

Views: 8149

Answers (2)

mklement0
mklement0

Reputation: 437100

You need to tell PowerShell which of your parameter sets is the default one:

[cmdletbinding(DefaultParameterSetName="First")]

This will allow you to invoke Do-ThisOrThat without any parameters as well as with a -SecondParameter value, and $FirstParam will have its default value in both cases.

Note, however, that based on how your parameter sets are defined, if you do specify an argument, you can't do so positionally - you must use the parameter name (-FirstParam or -SecondParam).

Upvotes: 7

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174445

This question is a bit ambiguous.

If you want to set the default parameter set, use the DefaultParameterSetName property in the [CmdletBinding()] attribute:

[CmdletBinding(DefaultParameterSetName='First')]

If, on the other hand you want to detect and infer whether $FirstParam has its default value inside the script, you can check which parameter set has been determined and whether FirstParam parameter was specified by the caller, like this:

if($PSCmdlet.ParameterSetName -eq 'First' -and -not $PSBoundParameters.ContainsKey('FirstParam')){ 
  <# $FirstParam has default value #> 
}

Upvotes: 3

Related Questions