在PowerShell中传递一个函数(带参数)作为参数 [英] Pass a function (with arguments) as a parameter in PowerShell

查看:841
本文介绍了在PowerShell中传递一个函数(带参数)作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经成功地在PowerShell中使用ScriptBlocks传递了无参数函数。但是,如果函数有参数,我无法使其工作。有没有办法在PowerShell中做到这一点? (v2优先)

$ $ p $ $ $ $ $ $ $ $ $ $ $ $ $ b返回$ x + $ y
}
函数Apply([scriptblock] $ s)
{
write-host($ s.Invoke(1,2))

然后

 应用{Add} 

将0写入控制台。 Apply不会调用 Add ,但不会传入任何参数(即使用0和0的默认[int]值)

好的,我在此处找到答案:



我想要 $ {function:Add} 而不是 {Add} 调用应用


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)

解决方案

Ok, I found the answer here:

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

这篇关于在PowerShell中传递一个函数(带参数)作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆