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?
What is $PSBoundParameters? $PSBoundParameters in PowerShell is an automatic variable that is populated based on the parameters used with a function. It is a hashtable whose keys contain the parameter name used, and values contain the argument/value passed in.
Optional arguments enable you to omit arguments for some parameters. Both techniques can be used with methods, indexers, constructors, and delegates. When you use named and optional arguments, the arguments are evaluated in the order in which they appear in the argument list, not the parameter list.
Optional arguments are values that do not need to be specified for a function to be called.
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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With