在另一个上下文的 ScriptBlock 中定义的引用函数

Reference Function Defined in a ScriptBlock from Another Context

我试图在脚本块外调用脚本块内声明的函数,但 PS 无法解析它。这是我的代码

  $ScriptBlock={

        function Get-Baz(){

            Write-Host "Baz executed"
        }
        function Get-Foo(){
            Write-Host "Foo executed"
        }
    }

    Get-Baz <--The term 'Get-Baz' is not recognized as the name of a cmdlet, function, script 

定义脚本块不会执行其中的任何内容。

通常您使用 the call operator & 执行脚本块,但在不同的范围内执行它并且不会工作。

相反,您需要在当前范围内执行脚本块。为此,请使用 dot sourcing operator .:

$ScriptBlock={

    function Get-Baz(){

        Write-Host "Baz executed"
    }
    function Get-Foo(){
        Write-Host "Foo executed"
    }
}

. $ScriptBlock

Get-Baz