header
header Register : : Login header
header
divider
menuleft
menuright
submenu
left

[August 25th, 2008] Check the home page regarding PowerShell related news from a brand new sponsor: Idera

Getting Closures
Last Post 08 Aug 2008 08:47 AM by 0ptikGhost. 0 Replies.
Printer Friendly
Sort:
PrevPrev NextNext
You are not authorized to post a reply.
Author Messages
0ptikGhostUser is Offline
New Member
New Member
Posts:1

--
08 Aug 2008 08:47 AM  

I want a function that returns a function that stores and uses the argument to the first function. An example should help clarify:

function add([int]$x) { return { param([int]$y) return $y + $x } }

$m2 = add 2
$m5 = add 5

&$m2 3 #expected:  5 actual: 3
&$m5 6 #expected: 11 actual: 6

After a little debugging I found that when add 2 executes the value of $x -eq 2 but when the returned script block is executed $x -eq $null.

A simple workaround is to evaluate $x and then use Invoke-Expression to create the script block:

function add([int]$x)
{
  return Invoke-Expression "{ param([int]`$y) return `$y + $x }"
}

$m2 = add 2
$m5 = add 5

&$m2 3 #actual:  5
&$m5 6 #actual: 11

Notice I had to escape $ to make this work. If I was concatenating strings I'd have to use something like return `$y + '$x'. I don't see this approach working well for all objects.

Is there anyway to get closures in PowerShell v1.0?

You are not authorized to post a reply.

Active Forums 4.1
right
   
footer Sponsored by Quest Software • SAPIEN Technologies • ShellTools, LLC • Microsoft Windows Server 2008 footer
footer