从进程块调用函数

dan*_*gph 3 powershell

我想从我的 PowerShell 脚本的 Process 和 End 块中调用一个特定的函数。这是最小的代码:

# MyScript.ps1

function MyFunc
{
    "hello"
}

Begin 
{
}

Process 
{
    MyFunc
}

End 
{
    MyFunc
}
Run Code Online (Sandbox Code Playgroud)

但是,此代码不会执行。我收到此错误:

开始:术语“开始”不是 cmdlet、函数、脚本文件或可运行程序的名称。

mkl*_*nt0 5

begin/ process/ end(和dynamic)块永远只能被用于作为唯一的顶层构建体

  • 脚本文件( *.ps1)

  • 在一个函数中

在这两种情况下,都不允许使用其他顶级代码(除了顶部的param(...)参数声明块),这是脚本内部MyFunc函数的放置违反的约束。

如果您希望脚本使用内部辅助函数,请将其放置在begin块中- 您可以根据需要从process/end块中调用它:

Begin {
  function MyFunc {
    "hello"
  }
}

Process {
  MyFunc
}

End {
  MyFunc
}
Run Code Online (Sandbox Code Playgroud)

以上产生:

hello
hello
Run Code Online (Sandbox Code Playgroud)

也就是说,块processend块都成功调用了MyFunc嵌套在begin块中的函数。

一般情况下,需要注意的是begin/ process/end块共享相同的局部范围,这也适用于变量,因此,同样的,你可以初始化的脚本/函数局部变量begin块和访问它的process模块,例如。
出于同样的原因,嵌套函数(例如MyFunc此处)对于封闭脚本/函数是本地的。