How to check if a PowerShell optional argument was set by caller

Powershell

Powershell Problem Overview


I have a script which takes these arguments:

param (
    [parameter(Mandatory=$true)][ValidateRange(1, [int]::MaxValue)]
    [Int]$startRevision,

    [parameter(Mandatory=$true)][ValidateRange(1, [int]::MaxValue)]
    [Int]$endRevision,

    [parameter(Mandatory=$false)][ValidateRange(1, [int]::MaxValue)]
    [Int]$stepSize = 10,

    [parameter(Mandatory=$false)]
    [String]$applicationToBuild
)

Since the last argument is optional, I would like to know if the argument is set. Is there any way to do this?

A default is not ok, since I don't want to use the variable if it is not set. I could use a default which is a "ThisIsNotSet" and check if the value is equal to this string, but is there a better solution?

Powershell Solutions


Solution 1 - Powershell

The automatic $PSBoundParameters variable is a hashtable-like object available inside functions whose .Keys property contains the names of all parameters to which arguments were explicitly passed on invocation.[1]

Thus, in your case, $PSBoundParameters.ContainsKey('applicationToBuild') tells you whether an argument was passed to -applicationToBuild (expression evaluates to $True) or not ($False).


Note: The advantage of this approach is that it is unambiguous, whereas testing for the parameter-variable type's default value, as in trbox' answer, doesn't allow you to distinguish between not passing an argument and explicitly passing the type's default value (the empty string, in this case).


[1] Note that parameters bound implicitly via default values are not included; including the latter would be helpful when passing arguments through to another function, as discussed in GitHub issue #3285.

Solution 2 - Powershell

$applicationToBuild is an empty string if nothing is passed in to the script, since the type of the parameter is [String].
So if the parameter "is not set", $applicationToBuild.Length will be 0.

You can use that when deciding whether the parameter should be used or not.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHoubieView Question on Stackoverflow
Solution 1 - Powershellmklement0View Answer on Stackoverflow
Solution 2 - PowershelltrboxView Answer on Stackoverflow