My Technical Notes

Friday, 10 January 2014

Lambdas in PowerShell

"Lambdas" or anonymous function blocks are supported in PowerShell. In PowerShell, we have two (maybe more) built-in parameters:

  • $_ which is the current pipeline object.
  • args which contains the arguments to the function.

To assign a lambda to a variable $f:


$f = { $args[0] * 2 }

To invoke $f with an argument of 5 which will return 10 (space between ampersand and variable name is not necessary):


& $f 5

Another way:


$f.Invoke(5)

To explicitly give name the parameter $p:


$g = { param($p) $p * 2 }
Which is invoked in exactly the same way (result is 42):

&$g 21

We use the pipeline variable $_ in the context of the pipeline. Given the below lambda:


$h = { $_ * 2 }

We can call it as we normally would within the context of a ForEach (returns 2, 8):


@(1, 4) | % $h

No comments: