GetNewClosure
$var = 'initial value for variable var'
$sb = {
write-host "Script block is invoked"
write-host " var = $var"
if (test-path variable:xyz) {
write-host " The variable xyz is defined, it's value is $xyz"
}
else {
write-host " The variable xyz is not defined"
}
}
$sb_closure = $sb.GetNewClosure()
$var = 'changed value for variable var'
$xyz = 'Value for xyz'
& $sb
& $sb_closure
If this code is placed into a script and executed, it prints:
Script block is invoked
var = changed value for variable var
The variable xyz is defined, it's value is Value for xyz
Script block is invoked
var = initial value for variable var
The variable xyz is not defined