Search code examples
powershellscriptblock

How to pass a named function as a parameter (scriptblock)


Let's take the classic first-order functions example:

function Get-MyName { "George" }

function Say-Hi([scriptblock]$to) {
  Write-Host ("Hi "+(& $to))
}

This works just fine:

Say-Hi { "Fred Flintstone" }

this does not:

Say-Hi Get-MyName

because Get-MyName is evaluated, not passed as a value itself. How do I pass Get-MyName as a value?


Solution

  • You have to pass Get-Myname as a scriptblock, because that's how you've defined the variable type.

    Say-Hi ${function:Get-MyName}