Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save a function into a variable?

Tags:

powershell

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
like image 284
XP1 Avatar asked Dec 07 '22 17:12

XP1


1 Answers

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
like image 199
Mathias R. Jessen Avatar answered Dec 14 '22 15:12

Mathias R. Jessen