通过“本地"反对后台工作 [英] Passing "native" object to background jobs
本文介绍了通过“本地"反对后台工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我想以一种或另一种方式实现的目标.
Here is what I'd like to achieve in one way or another.
我有一个自定义程序集定义了一些对象.在我的脚本中,我创建了一个我想传递给脚本块的自定义对象,并保持该对象的行为.
I have a custom assembly defining some objects. In my script, I create a custom object that I'd like to pass to a script block, keeping that object behavior.
Add-Type -AssemblyName MyCustomDLL
$global:object = new-object MyCustomDLL.MyCustomObject()
$object | gm
$jobWork = { param ($object) $object | gm } # I'd like to keep my object behavior in that block
$job = Start-Job -ScriptBlock $jobWork -ArgumentList $object
Wait-Job $job
Receive-Job $job
我怎样才能做到这一点或达到同样的效果?感谢您的帮助
How can I do that or achieve the same effect? Thanks for your help
推荐答案
您可以使用 PowerShell
和 BeginInvoke
、EndInvoke
代替后台作业.这是一个简单但有效的示例,它在作业"中传递活动对象,在那里更改它,获得结果:
Instead of background jobs you may use PowerShell
with BeginInvoke
, EndInvoke
. Here is the simple but working example of passing a live object in a "job", changing it there, getting the results:
# live object to be passed in a job and changed there
$liveObject = @{ data = 42}
# job script
$script = {
param($p1)
$p1.data # some output (42)
$p1.data = 3.14 # change the live object data
}
# create and start the job
$p = [PowerShell]::Create()
$null = $p.AddScript($script).AddArgument($liveObject)
$job = $p.BeginInvoke()
# wait for it to complete
$done = $job.AsyncWaitHandle.WaitOne()
# get the output, this line prints 42
$p.EndInvoke($job)
# show the changed live object (data = 3.14)
$liveObject
这篇关于通过“本地"反对后台工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文