Anonymous functions in Powershell

While going through a number of javascript tutorials there were one thing that I wondered if it existed in Powershell.

Which is the notion of the “anonymous function”.
In Powershell this is more likely to be refered to as a “script block”.

The use case (in my opinion) is short repetitive code blocks that you want to call with different values, throughout your script/function.
Any more then that it’s probably better to just create a normal function as it will be be easier to follow and maintain.

Anyway, how do we create an “anonymous function”.
For example lets say you want to calculate the volume of a box in different parts of your code.
You could then create a variable holding a script block to do it.

# The variable containing the script block
$calculateVolume={param($width,$height,$depth) $width*$height*$depth}

# Calling the anonymous function using & before the variable.
&$calculateVolume 2 5 10

You can extend the script block between the curly braces just as any other function.
But then you might consider creating a normal function to “modularize” your code, rather than creating a big monolithic script/function.

Finally I want to leave a short example of something that I’ve found useful recently.
Which will examine a value and determine if the value is odd or even.
Then execute some code depending on if it’s odd or even.

# The IF statement will return true if it's odd and false if it's even.
$oddValue={param([int]$value) if($value % 2 -eq 1){$true}else{$false}}

# Some value to evaluate
$value = 5

# Calling the anonymous function in a switch statement.
switch(&$oddValue $value)
{
    $true {Write-Output "Some code if the value is odd";break}
    $false {Write-Output "Some code if the value is even";break}
}

Later on in the code when using it in the switch statement it looks much cleaner in my opinion.
Again, if you’re only going to use it once in your script/function, you may as well just use that one ‘IF’ statement.