Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"

like image 604
Mark Allison Avatar asked Oct 25 '25 16:10

Mark Allison


1 Answers

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).

like image 129
mklement0 Avatar answered Oct 28 '25 08:10

mklement0