首页 > 解决方案 > 如何引用父作用域中定义的 PowerShell 函数?

问题描述

我正在编写一个运行几个后台作业的 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:. 不过,我不能用函数来做到这一点;按原样运行此代码会返回错误:

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

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

标签: functionpowershellscope

解决方案


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

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

这对于具有作用域的变量值来说是微不足道的,但对于函数来说不太明显,但是可以通过命名空间变量表示法传递函数体来使其具有一些重复性:$using:

# 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'如预期的那样,上述输出。


推荐阅读