2

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?

8DH
  • 2,022
  • 23
  • 36

1 Answers1

2

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.

Roman Kuzmin
  • 40,627
  • 11
  • 95
  • 117
  • 1
    Thanks! Eventually I found that I could use $fun=${Function:\bar} but I'm not quite sure which alternative is more intention revealing. – 8DH Oct 16 '12 at 09:54
  • Ah, this is an interesting find. It is shorter, at least, or maybe even faster. I'll play with it a little. – Roman Kuzmin Oct 16 '12 at 10:08
  • 1
    Yes, it is also faster. It is useful to know. I can update my answer with this extra option for completeness or you may update your question with this useful information. – Roman Kuzmin Oct 16 '12 at 10:15