There are situations where you need to create a script block, save it into variable and then execute it once or multiple times. Simply said, [ScriptBlock] is just an anonymous function so if you do this:

$scriptBlock = { $someVar }
& $scriptBlock

Then you will get someVar variable from the current scope or from the parent scope (dynamic scoping).

But what to do if you need to create a script block and keep intact all values of all variables? PowerShell 2.0 introduction method to get closure: ScriptBlock.GetNewClosure(). Simply said, GetNewClosure method causes that script block remembers the values that were passed in the first time.

Example without get closure

$var = 'First'
$scriptblock =
{
    Value: {0}' -f $var
}
& $scriptblock

$var = 'Second'
& $scriptblock

Output

Value: First
Value: Second

Example with get closure

$var = 'First'
$scriptblock =
{
    Value: {0}' -f $var
}.GetNewClosure()
& $scriptblock

$var = 'Second'
& $scriptblock

Output

Value: First
Value: First
« Previous Next »