How to copy values of variables into PowerShell Script Block and keep it intact (remember it)?


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

Leave a Reply

Your email address will not be published. Required fields are marked *

Active Directory Advanced function AlwaysOn Availability Groups AlwaysOn Failover Cluster Instances Building Cloud Cloud Cluster Cmdlet Database Deployment Design DFS Domain Controller DSC Fabric Failover Clustering File Server Group Policy Hardware Profile Host Hyper-V Installation Library Library Asset Library Server Network Operations Manager Orchestrator PowerShell PowerShell User Group PowerShell Workflow Security Service Manager SQL Server Storage System Center Template Time Time Synchronization Tips Virtual Machine Virtual Machine Manager VM Network VM Template Windows Server 2012 R2