[英]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:
。 不過,我不能用函數來做到這一點; 按原樣運行此代碼會返回錯誤:
The term 'Do-TheThing' is not recognized as the name of a cmdlet, function, script file, or operable program.
我的問題是:我的后台作業如何使用我在更高的 scope 中定義的小型實用程序 function?
If the function in the higher scope is in the same (non-)module scope in the same session , your code implicitly sees it, due to PowerShell's dynamic scoping.
但是,后台作業在單獨的進程(子進程)中運行,因此調用者的 scope 中的任何內容都必須顯式傳遞給這個單獨的 session。
這對於變量值來說是微不足道的,使用$using:
scope ,但對於函數來說不太明顯,但它可以通過命名空間變量表示法傳遞函數體來實現一些重復:
# 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'
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.