I'm trying to validate if a parameter is present, see example code:
function Test-Function {
[CmdletBinding()]
Param (
[Parameter(Mandatory = $false)]
[ValidateNotNullOrEmpty()]
[Int64]$TestParam
)
if ($TestParam) {
Write-Host "Parameter is present.."
# Do stuff ...
}
}
# Execute the function
Test-Function -TestParam 1
Parameter is present..
# Pass the value 0
Test-Function -TestParam 0
<no output>
Is there a way to fix this? The type must be an integer, not [String]
CodePudding user response:
Use the $PSBoundParameters
automatic variable to inspect parameter binding results for the current invocation:
if($PSBoundParameters.ContainsKey('TestParam')){
"Caller definitely provided an argument for -TestParam"
}
Note that an argument is considered bound regardless of whether the binding was positional or if it was explicitly bound by name:
function f {
param(
[Parameter(Position = 0)]
$TestParam
)
if($PSBoundParameters.ContainsKey('TestParam')){
"Caller definitely provided an argument for -TestParam"
}
}
PS ~> f -TestParam 123
Caller definitely provided an argument for -TestParam
PS ~> f 123
Caller definitely provided an argument for -TestParam
In the second example, we never explicitly bind 123
to -TestParam
, but because TestParam
is the first positional parameter, 123 is bound to $TestParam
, and thus $PSBoundParameters.ContainsKey('TestParam')
returns $true