Search notes:

GetNewClosure

Simple Example

$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

Dynamic Module

GetNewClosure creates a dynamic module:
PS: 1 C:\Users\rene> $sb = {}
PS: 2 C:\Users\rene> $sb.module
PS: 3 C:\Users\rene> $sbNew = $sb.GetNewClosure()
PS: 5 C:\Users\rene> $sbNew.Module

ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Script     0.0        __DynamicModule_50d49a52-7dd6-41...

See also

Creating a script block that captures the value of an (external) variable using GetNewClosure.
System.Management.Automation.ScriptBlock

Index