Search code examples
functionpowershellparametersblockdefaults

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


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?


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.