如何引用父作用域中定义的 PowerShell 函数?

How to refer to a PowerShell function defined in a parent scope?

我正在编写一个运行几个后台作业的 PowerShell 脚本。其中一些后台作业将使用相同的一组常量或实用函数,如下所示:

$FirstConstant = "Not changing"
$SecondConstant = "Also not changing"
function Do-TheThing($thing)
{
    # Stuff
}

$FirstJob = Start-Job -ScriptBlock {
    Do-TheThing $using:FirstConstant
}

$SecondJob = Start-Job -ScriptBlock {
    Do-TheThing $using:FirstConstant
    Do-TheThing $using:SecondConstant
}

如果我想在子作用域中共享变量(或在本例中为常量),我会在变量引用前加上 $using: 前缀。不过,我不能用函数来做到这一点; 运行 此代码原样 returns 错误:

The term 'Do-TheThing' is not recognized as the name of a cmdlet, function, script file, or operable program.

我的问题是:我的后台作业如何使用我在更高范围内定义的小型实用函数?

如果较高作用域中的函数在相同会话中的相同(非)模块作用域中,您的代码隐式看到它,由于 PowerShell 的动态范围。

但是,后台作业 运行在单独的进程(子进程)中,所以调用者范围内的任何东西都必须显式传递给这个单独的会话。

这对于 变量 值来说是微不足道的,$using: scope, but less obvious for functions, but it can be made to work with a bit of duplication, by passing a function's body via :

# The function to call from the background job.
Function Do-TheThing { param($thing) "thing is: $thing" }

$firstConstant = 'Not changing'

Start-Job {

  # Define function Do-TheThing here in the background job, using
  # the caller's function *body*.
  ${function:Do-TheThing} = ${using:function:Do-TheThing}

  # Now call it, with a variable value from the caller's scope
  Do-TheThing $using:firstConstant

} | Receive-Job -Wait -AutoRemoveJob

以上输出 'thing is: Not changing',符合预期。