Jes*_*eTG 1 powershell scope function
我正在编写一个运行几个后台作业的 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
}
Run Code Online (Sandbox Code Playgroud)
如果我想在子作用域中共享变量(或者在本例中为常量),我会在变量引用前面加上$using:. 但我不能用函数来做到这一点;按原样运行此代码会返回错误:
The term 'Do-TheThing' is not recognized as the name of a cmdlet, function, script file, or operable program.
Run Code Online (Sandbox Code Playgroud)
我的问题是:我的后台作业如何使用我在更高范围内定义的小型实用函数?
如果较高作用域中的函数位于同一会话中的相同(非)模块作用域中,则由于 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
Run Code Online (Sandbox Code Playgroud)
上面的输出'thing is: Not changing',符合预期。
| 归档时间: |
|
| 查看次数: |
913 次 |
| 最近记录: |