从Powershell中的闭包调用函数

从Powershell中的闭包调用函数,powershell,Powershell,我有一个函数,它返回一个调用另一个函数的脚本块。(这听起来可能过于复杂,但在实际代码中是有意义的。) 它在ISE中工作,但在常规控制台中不工作 我做错了什么,还是这是PowerShell中的一个bug?有解决办法吗 以下是一些显示问题的最低限度代码: function SomeFunc([string]$name) { "Hello, $name!" } function GetBlock([string]$name) { { SomeFunc $name }.GetNewCl

我有一个函数,它返回一个调用另一个函数的脚本块。(这听起来可能过于复杂,但在实际代码中是有意义的。)

它在ISE中工作,但在常规控制台中不工作

我做错了什么,还是这是PowerShell中的一个bug?有解决办法吗

以下是一些显示问题的最低限度代码:

function SomeFunc([string]$name)
{
    "Hello, $name!"
}

function GetBlock([string]$name)
{
    { SomeFunc $name }.GetNewClosure()
}

$block = GetBlock("World")

& $block
请将代码放入文件并执行该文件以查看错误。如果您只是将其粘贴到控制台中,则不会出现错误

当我按F5在ISE中运行它时,我得到了预期的结果:

Hello, World!
但是,当我在常规控制台中运行它时,我得到一个错误:

SomeFunc : The term 'SomeFunc' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At E:\scratch\Untitled4.ps1:8 char:7
+     { SomeFunc $name}.GetNewClosure()
+       ~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (SomeFunc:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
这是我的
$pVersionTable

Name                           Value
----                           -----
PSVersion                      5.1.16299.251
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.16299.251
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

将脚本块中调用的函数的作用域设置为
global
,可以得到所需的
Hello,World

function global:SomeFunc([string]$name)
{
    "Hello, $name!"
}

请注意,使
SomeFunc
global会使其在脚本执行完成后保持可用,因此您需要小心命名,以避免屏蔽其他命令。

我刚刚将您的代码复制到控制台中,并得到了“Hello,World!”@MikeShepard,嗯,如果您将其粘贴到控制台中,它似乎可以工作,但如果从文件运行,则不会。我会更新我的问题。谢谢。
GetNewClosure
仅捕获变量,不捕获函数。它还可以这样做,即只有全局范围可用于关闭。如果您不使用“Run(F5)”ISE命令,而是在控制台中键入文件名(假设会话是干净的,并且在全局范围中尚未定义函数SomeFunc),则在ISE中的行为方式与此相同。