Using closure to capture the variable value in a script-block

You can’t use New-Item to create new functions or aliases. It only works for files and directories.

But you can use Set-Item to create new functions and aliases.

How would I go about making a bunch of functions via a loop? The following code creates functions named Hello-<num> which output <num> when run.

Does this work?

And there lies the problem. Instead of each definition containing the number as it’s supposed to be, they all contain the variable $i. And since $i is 10 when the foreach loop terminated, all functions return the number 10.

I can test this by setting $i to a different number:

What I need is for $i in the Set-Item script-block to not be left as a variable, but to be “captured” (for lack of a better word) and set to whatever the value of the variable is at the time the script-block is created.

If you examine the members of a script-block you’ll notice a method called GetNewClosure(). That’s what I need to use here. This method “closes off” (like “closing a deal” or “let’s close somebody”, similar to “capturing somebody”) all variables in the script-block when it’s created.

Good to know!

Closures work with function parameters too. No side-effects as far as I know.