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

て烟熏妆下的殇ゞ 提交于 2019-12-05 02:51:58
Rob

Ok, I found the answer here:

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

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"

Don't you want to do something like this?

function Add([int] $x, [int] $y)  
{ 
    return $x + $y 
}

function Apply([scriptblock] $s)    
{ 
    Write-Host $s.Invoke($args)
}

Apply { Add 1 2}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!