Pass a function (with arguments) as a parameter in PowerShell
Asked Answered
A

2

9

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)

Ambrogino answered 2/9, 2013 at 9:13 Comment(0)
A
15

Ok, I found the answer here:

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

Ambrogino answered 2/9, 2013 at 9:55 Comment(1)
Trap for young players: You can't have any spaces between the braces and the function details. So ${ function:Add } (leading and trailing spaces), ${ function:Add} (leading space) or ${function:Add } (trailing space) will all fail with error You cannot call a method on a null-valued expression. ${function:Add}, without either leading or trailing space, works fine.Crouse
W
1

There is a much cleaner way to do this using the PowerShell function provider. I needed to be able to run functions from other source files with variable numbers of arguments based on an XML file provided at run time.

In developing this I wrote a small "Hello World" tester in two source files which should be fairly self-explanatory (the magic line is "$x = (& $func $parm)"):

  1. "Hello.ps1" - The remote function

    function Hello ($in) {
     
        write-Host "Hello $in"
    }
  1. "Hello2.ps1" - The executing routine

    function exec-script ($file, $func, $parm) {
       
       Invoke-Expression $file    
       
       $x = (& $func $parm)
       
       $x
        
       }
    
    exec-script -file ".\Hello" -func "Hello" -parm "World"
Washtub answered 16/12, 2014 at 21:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.