从Powershell中的闭包调用函数

时间:2018-03-23 01:24:20

标签: powershell

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

它适用于ISE,但不适用于常规控制台。

我做错了,或者这是PowerShell中的错误?有解决方法吗?

以下是显示问题的一些最小代码:

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

这是我的$psversiontable

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

1 个答案:

答案 0 :(得分:2)

将脚本块中调用的函数范围设置为global,得到所需的Hello, World!

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

请注意,使SomeFunc全局变为导致它在脚本完成执行后仍然可用,因此您需要注意命名以避免屏蔽其他命令。

相关问题