alex2k8
alex2k8

Reputation: 43204

How can I know that PowerShell function parameter is omitted

Consider such function:

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

We can call it:

Test -foo $null
Test

How can I know when the -foo was omitted, and when it was $null?

Upvotes: 3

Views: 1275

Answers (3)

zdan
zdan

Reputation: 29450

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

See this blog post that discusses it.

Upvotes: 4

alex2k8
alex2k8

Reputation: 43204

The 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

Upvotes: 1

Richard
Richard

Reputation: 109100

Unless it is possible to trap exceptions thrown from param statement (and since param has to be the first, I can't see this would work):

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

Then I can't see a way (you get the same thing with [switch] parameters: default or explicitly -mySwitch:$false).

Upvotes: 1

Related Questions