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

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.


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

Tags:

Powershell