Thursday, January 30, 2014

PowerShell - When is a function not a function?

Answer - When it is a codeblock!

I think we all know that a codeblock is anything between curly braces:

{
   Write-Host "Hello World"
}

And a typical function is constructed and used thus:

Function SayHello
{
   Write-Host "Hello World"
}

SayHello

What is not commonly done is treating a codeblock similar to a function, in this sense a codeblock is known as an 'anonymous function' (because it has no name). As usual this is best shown as an example:

$MyCodeBlock = {
   Write-Host "Hello World"
}

Which can be run in three different ways:

&$MyCodeBlock

or

$MyCodeBlock.Invoke

or

Invoke-Command $MyCodeBlock

Now, of course with a function you can pass parameters and run it thus:

function MyFunction
{
   Param([Int] $x, [int] $y)
   Write-Host "I am a function, and can be passed variables"
}

MyFunction 1 2

Can we really do that with a script block? You bet we can...

$MyCodeBlock = {
   Param $x, $y)
   Write-Host "I'm not a function, but I can be passed variables"
}

# Run Function
MyFunction 1 2

#Run ScriptBlock using ampersand
&$MyCodeBlock 3 4

#Run ScriptBlock using Invoke
$MyCodeBlock.Invoke(5,6)

#Run ScriptBlock using Invoke-Command
Invoke-Command $MyCodeBlock -argumentlist 7, 8

So you see the difference between a function and a scriptblock becomes quite weak.

Cheers!



No comments:

Post a Comment