80

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?

2 Answers 2

144

The automatic $PSBoundParameters variable, available inside functions and scripts, contains a dictionary whose entries comprise the names and values of all parameters to which arguments were explicitly passed on invocation.[1]

Its .Keys property contains all such parameter names, and the .ContainsKey() method can be used to test for the presence of a given parameter by name.

Thus, in your case, $PSBoundParameters.ContainsKey('applicationToBuild') tells you whether an argument was passed to the -applicationToBuild parameter (namely if the 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.

Sign up to request clarification or add additional context in comments.

Comments

5

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

3 Comments

Unless you need to distinguish between the case of "not passed" VS "passed empty".
You’re right. In any case, mklement0’s solution is much better and is the one that should be used.
this is not reliable. I passed a value to one param and no value to another. $<param>.Length was equal to 1 for both of them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.