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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With