Using Closures

by Oct 19, 2012

Script blocks are dynamic by default, so variables in a script block will be evaluated each time the script block runs.

By turning a script block in a "closure", it keeps the state of the variables. Here is an example:

PS> $var = 'A'
PS> $scriptblock = { $var }
PS> & $scriptblock
A
PS> $var = 'B'
PS> & $scriptblock
B
PS>
PS> $var = 'D'
PS> $closure = $scriptblock.GetNewClosure()
PS> $var = 'E'
PS> & $closure
D
PS> $var = 'F'
PS> & $closure
D

Note that the closure script block will always return "D" because that was the value of $var when the closure was created.

Twitter This Tip! ReTweet this Tip!