Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a function (with arguments) as a parameter in PowerShell

I've been successfully passing no-argument functions around in PowerShell using ScriptBlocks. However, I can't get this to work if the function has arguments. Is there a way to do this in PowerShell? (v2 preferably)

Function Add([int] $x, [int] $y)  
{ 
  return $x + $y 
}
Function Apply([scriptblock] $s)    
{ 
    write-host ($s.Invoke(1,2)) 
}

Then

Apply { Add } 

writes 0 to the console. Apply does invoke Add, but doesn't pass any arguments in (i.e. uses the default [int] values of 0 and 0)

like image 638
Rob Avatar asked Sep 02 '13 09:09

Rob


1 Answers

Ok, I found the answer here:

I wanted ${function:Add} rather than { Add } in the call to Apply.

like image 67
Rob Avatar answered Sep 20 '22 15:09

Rob