Dollar signs, function keywords and script blocks in powershell

Question:

I have this powershell script:

This works – it outputs Value is processed by Func3 and is processed by Func2 and is processed by Func1 – but I am confused at two things:

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

What does the $function:function-name.Invoke code in Func3 mean? I sense that it is using script block functionality, since the Invoke method is called, but it’s not clear to me how $function.function-name is a script block.

Answer:

function: is the PsDrive for the Function provider. All functions are stored on this drive. There are other PsDrives including variable: and env:. Check out Get-PsProvider and Get-PsDrive for more.

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

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

The contents of functions are script blocks, which is why it’s being used as the scriptblock parameter for Invoke-Command.

Every thing in the function: psdrive will be a script block, and scriptblock objects have an Invoke method which allows you to execute them.

Source:

Dollar signs, function keywords and script blocks in powershell by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply