Powershell script blocks are not closures

I've been experimenting some more with the script blocks, and I've found that my description of them as sort-of-closures in my other post is wrong. Here is an example that demonstrates it:

PS > function g { param($block) $a=234; &$block; }
PS > function f { $a=123; g { "The value of `$a is $a" } }
PS > f
The value of $a is 234

They simply use the variable values from the nearest enclosing block in the same module.

 But there is a way to get a sort-of-closure too:

PS > function f { $a=123; g { "The value of `$a is $a" }.GetNewClosure() }
PS > f
The value of $a is 123

The sort-of part is because the value of $a in f() cannot be changed from inside the script block.

My next idea was to use the references but that didn't quite work out either:

PS > function f { $a=123; g { $aa=[ref]$a; "The value of `$a is $($aa.value)"; $aa.value = 10; "The new value of `$a is $($aa.value)" }.GetNewClosure(); $a }
PS > f
The value of $a is 123
The new value of $a is 10
123

The problem is GetNewClosure() doesn't create a reference to the variables in the current scope but just copies their values to the new variables. Thus [ref] gets a reference to the copy, and this copy is not visible inside the function f().

Without GetNewClosure, the script block ends up changing the value of the variable in the nearest scope, which happens to be in g():

PS > function g { param($block) $a=234; &$block; "in g `$a is $a" }
PS > function f { $a=123; g { $aa=[ref]$a; "The value of `$a is $($aa.value)"; $aa.value = 10; "The new value of `$a is $($aa.value)" }; $a }
PS > f
The value of $a is 234
The new value of $a is 10
in g $a is 10
123

The way to make it behave like a proper closure, being able to change the variables in the original scope, is to get the reference directly in f() and then fixate it with GetNewClosure():

PS C:\Users\sbabkin> function f { $a=123; $aa=[ref]$a; g {"The value of `$a is $($aa.value)"; $aa.value = 10; "The new value of `$a is $($aa.value)" }.GetNewClosure(); $a }
PS C:\Users\sbabkin> f
The value of $a is 123
The new value of $a is 10
in g $a is 234
10

It finally works but oh so painfully.