Dollar signs, functional keywords, and script blocks in powershell

I have this powershell script:

function Func1 ($val) { Write-Host "$val is processed by Func1"; } function Func2($val) { Invoke-Command -ScriptBlock ` ${function:Func1} -ArgumentList "$val is processed by Func2 and"; } function Func3($val) { $function:Func2.Invoke("$val is processed by Func3 and"); } Func3 "Value"; 

This works - it outputs the value handled by Func3 and handled by Func2 and handled by Func1 - but I am confused in two things:

What does the code $ {function: function-name} mean (that is, a dollar sign followed by an opening brace, followed by a function , followed by a colon, followed by the name of the function, followed by a closing brace) Func2 mean? I see that it calls Func1, but I don’t understand why it works.

What does $ function: function-name.Invoke code mean in Func3? I feel like it uses the functionality of the script block, as the Invoke method is called, but it is not clear to me how $ function.function-name is a script block.

+4
source share
1 answer

function: is PsDrive for the function provider. All functions are stored on this disk. Other PsDrives exist, including variable: and env: See Get-PsProvider and Get-PsDrive .

To access a function from the function: drive (to get its contents, not to call it), use $function:foo , where foo is the name of the function that you want to access.

Curly braces are only required when accessing a variable that has a special character in its name.

The contents of the script block functions, so it is used as the scriptblock parameter for Invoke-Command .

Every thing in function: psdrive will be a script block, and scriptblock objects have an Invoke method that allows them to be executed.

+5
source

All Articles