Checking for bound parameters

I recently read an email where someone was asking how they could check in their function if a value had been provided to one of the parameters.  Consider for example,


 







001
002
003
004
005
006
007
008


function foo
{
  param(
    $x
  )
    
  #If $x was given a value do something, else do something else.
}


 


The usual way I’ve seen people deal this problem is by providing a default value which gets assigned to $x in the case that a value wasn’t provided by the caller and then checking for that value. 


 







001
002
003
004
005
006
007
008


function foo
{
  param(
    $x = $null
  )
  
  # Check for $x being null.
}


 


That works in the majority of cases, but let’s say that you wanted to differentiate between a default $null value and $null being passed by the caller.  What would you do?


If you’re on v2, a simple solution is to look at $PSBoundParameters.  It’s a hashtable containing the parameters that were bound and what values were bound to them.  Try this:


 


 







001
002
003
004
005
006
007
008
009


function foo
{
  param(
    $x,
    $y
  )
  
  $PSBoundParameters
}


 


PS >foo 1


 


Key                                                                       Value


                                                                       —–


x                                                                             1


 


 


PS >foo 1 ‘foo’


 


Key                                                                       Value


                                                                       —–


x                                                                             1


y                                                                           foo


 


 


 


With $PSBoundParameters containing all the bound parameters, to check if a parameter was given a value, it’s a simple matter of checking if $PSBoundParameters contains a key for it.


 







001
002
003
004
005
006
007
008
009
010
011
012
013
014
015




function foo
{
  param(
    $x
  )
  
  if ($PSBoundParameters.ContainsKey(‘x’))
  {
    write-host ‘X Bound!’
  }
}


 


 


– Marcel Ortiz Soto [MSFT]