Creating a Powershell Function Using Set-Item and GetNewClosure

I am trying to create a function that itself can create functions through the Set-Item command, where I pass the script block for the new function to the -Value Set-Item parameter. I am facing a problem where using GetNewClosure in the script block does not seem to work, and I just don't know what I'm doing wrong.

In the code below, first I create a function manually (testFunc), which works as intended, in this parameter $ x to 2 after creating the function will not return function 2; instead, it returns 1 because it was the value of $ x at the time the function was created. But when I try to do the same through the make-function, the behavior changes.

I'm sure I'm missing something small.

> $x = 1
> $block = {$x}.GetNewClosure()
> Set-Item function:global:testFunc -Value $block
> testFunc
1 

> $x = 2
> testFunc
1 # still 1 because of GetNewClosure - this is expected behavior

> $x = 1
> function make-function { $block2 = {$x}.GetNewClosure()
       Set-Item function:global:testFunc2 -Value $block2
  }
> make-function
> testFunc2
1 

> $x = 2
> testFunc2
2 # Why is it not returning 1 in this case? 
+4
1

MSDN, :

, .

GetNewClosure() , "" , .. . :

function Make-Function {
   $x = $global:x
   $function:global:testFunc2 = {$x}.GetNewClosure()
}

, , GetNewClosure() , :

$m = (Get-Command testFunc2).Module
& $m Get-Variable -Scope 0
+6

All Articles