Function reference parameter

Example of function reference parameter:

function Test
{
    param(
          [ref]$Status
          $SomeOtherVariable
    )

    $Status.Value = $true
}
  • Can $Status parameter be declared not mandatory?
  • How would you check whether $Status parameter is bound by the caller? (in order to use it within function)

I mean which of the following 2 possible implementations would you use and why? (which is better for performance?)

Implementation 1:

if ($PSCmdlet.MyInvocation.BoundParameters.ContainsKey("Status"))
{
     $Status.Value = $true
}

Implementation 2:

param(
          [Parameter(ParameterSetName = "SetName")]
          [ref]$Status,

          $SomeOtherVariable
    )

if ($PSCmdlet.ParameterSetName -eq "SetName")
{
      $Status.Value = $true
}

Caller may use any of the 2 calls, with or without bounding to reference, so which implementation is better?
In addition to performance benefits (if any), are there any other benefits of one implementation vs the other?

$Var

# Option1: Reference is bound
Test -Status $Var

# Option2: Reference is not bound
Test

Is there some other way to implement checking whether the reference parameter was bound by the caller?

Any parameter which is not set explicitly as mandatory are optional.

This is how mandatory parameter is.

Param(
   [Parameter(Mandatory)]
   [Ref]$Status
)

If Mandatory is not mentioned in Parameter attribute, then it becomes optional.

And the bestway to check if a parameter is bound or not is using $PSBoundParameters built-in hastable. It will have the list of bound parameters, its ultimately same as $PSCmdlet.MyInvocation.BoundParameters

1 Like

I use the built in $PSBoundParameters so rarely that I forgot it exists :grinning:

Your answer to use something that is already populated by PS makes a lot of sense for performance coding, thanks!