如何引用在父作用域中定义的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.

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

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

但是,后台作业单独的进程(子进程(中运行,因此调用方作用域中的任何内容都必须显式传递到此单独的会话。

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

# 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'

最新更新