Have you ever created scriptblocks on the fly, say in a foreach loop, and they totally mess up because they all have the same value?
This is something sort of advanced, and typically used when you’re proxying an object.
The most basic example would be, taken from (http://www.powershellcommunity.org/Forums/tabid/54/aff/1/aft/2506/afv/topic/Default.aspx)
function add([int]$x) { return { param([int]$y) return $y + $x } }
$m2 = add 2
$m5 = add 5
&$m2 3 #expected: 5 actual: 3
&$m5 6 #expected: 11 actual: 6
The value for $x is $null for both.
Why is that? Its because $x is $null in the local scope, the script block doesn’t remember the $x.
If we do
$x = 1000
&$m2 3 #expected: 5 actual: 1003
&$m5 6 #expected: 11 actual: 1006
This can be fixed in V2 using closures.
function add([int]$x) { return { param([int]$y) return $y + $x }.GetNewClosure() }
$m2 = add 2
$m5 = add 5
&$m2 3 #expected: 5 actual: 5
&$m5 6 #expected: 11 actual: 11
Closures are also great for ScriptProperties and ScriptMethods.
Hope this helps,
Ibrahim
0 comments