Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top