Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dollar signs, function 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 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.

like image 279
Tola Odejayi Avatar asked Mar 24 '13 06:03

Tola Odejayi


1 Answers

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.

like image 110
Andy Arismendi Avatar answered Sep 26 '22 20:09

Andy Arismendi