How to specify a function as the default of a scriptblock parameter in a PowerShell function?

567 Views Asked by At

Given these powershell functions where foo takes a scriptblock as parameter:

function bar($name)
{
    "Hello World $name"
}

function foo([scriptblock]$fun={})
{
    &$fun "Bart"
}

Is it possible to specify the function bar as default for $fun instead of {} in function foo?

1

There are 1 best solutions below

3
On BEST ANSWER

Yes, it is possible. For example, this way works for passing a function in:

foo ((get-command bar).scriptblock)

In your case it prints

Hello World Bart

Thus, in order to use it as the default parameter:

function foo([scriptblock]$fun=(get-command bar).scriptblock)
{
    &$fun "Bart"
}

Now just calling

foo

gets the same result.