I have the following code (simplified, this is not my actual use case):
$actions = @()
@(1,2,3) | ForEach-Object {
$localCopy = $_
$actions += {Write-Output $localCopy}
}
$actions | ForEach-Object { $_.Invoke() }
It outputs:
3
3
3
However, the output I want is:
1
2
3
In something like C#, assigning the $localCopy variable would be enough to create a new, local variable that the delegate would reference when called. However, Powershell has different scoping - I am using Powershell 3.0, so the delegate gets invoked in its own scope (see this question). I tried playing with the $local: prefix on $localCopy, but that didn't work (as expected given the scoping rules).
So, if a delegate is invoked in its own scope, is this just impossible to accomplish? How can I assign a temporary variable that is available when the delegate is executed? I understand there's probably a solution to this using NewScriptBlock, but that just seems excessively complex to what I'd think would be a simple operation.