6

How to save a function into a variable?

function sayHello {
    write-host Hello, world!
}

$a = sayHello

Then, I want to call $a.

Another example:

$a = get-childItem
$a -name
XP1
  • 6,910
  • 8
  • 54
  • 61
  • 1
    Why would someone wants to do that ? and $a -name will throw error because $a will hold the contents of the get-childitem. not the the dot net library class to execute that from $a. – Ranadip Dutta Jun 28 '17 at 05:20

1 Answers1

21

You can refer to the function definition itself using the function variable scope qualifier:

$helloFunc = $function:sayHello

Now you can invoke it using the call operator (&):

& $helloFunc

The call operator supports parameters as well:

PS C:\> function test-param {param($a,$b) $b,$a |Write-Host}
PS C:\> $tp = ${function:test-param}
PS C:\> & $tp 123 456
456
123
PS C:\> & $tp -b 123 -a 456
123
456
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206