Use Closures to Lock Variables to Script Blocks

by May 14, 2015

When you use variables inside a script block, the variables are evaluated when you run the script block.

To lock variable content, you can create a new "Closure". Once you do this, the script block takes the variable values that were assigned at the time when you created the closure.

$info = 1

$code = 

$code = $code.GetNewClosure()

$info = 2

& $code

Without the closure, the script block should show "2" because $info contains the value 2 at the time of execution. Because of the closure, the script block instead takes the value that was assigned to $info when the closure was created.

Twitter This Tip! ReTweet this Tip!