Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check for parameter in function – accept input value 0

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]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading