How can I find out that the PowerShell function parameter is omitted

Consider the following function:

function Test($foo, $bar)
{
  ...
}

We can call it:

Test -foo $null
Test

How can I find out when -foo was omitted and when it was $ null?

+3
source share
3 answers

If you are using Powershell V2 or later, you can use the $ PSBoundParameters variable, which is a dictionary that lists all the related parameters in the current scope.

See this blog post discussing it.

+4
source

If it is not possible to exclude exceptions from the param command (and since param should be the first, I don't see this work):

function {
  trap { "Something failed" }
  param($foo = $(throw "Foo not specified"))
  ...

( [switch]: -mySwitch:$false).

+1

Solution based on Richard's idea:

$missed = "{716C1AD7-0DA6-45e6-854E-4B466508EB96}"

function Test($foo = $missed, $bar)
{
    if($foo -eq $missed) {
        Write-Host 'Missed'
    }
    else
    {
        Write-Host "Foo: $foo"
    }
}

Test -foo $null
Test
+1
source

All Articles