gpt4 book ai didi

powershell - 将 "native"对象传递给后台作业

转载 作者:行者123 更新时间:2023-12-04 05:53:34 27 4
gpt4 key购买 nike

这是我想以一种或另一种方式实现的目标。

我有一个定义一些对象的自定义程序集。在脚本中,我创建了一个自定义对象,该对象将传递给脚本块,并保持该对象的行为。

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

我该怎么做或达到相同的效果?谢谢你的帮助

最佳答案

代替后台作业,您可以将PowerShellBeginInvokeEndInvoke结合使用。这是在“作业”中传递事件对象,然后在其中进行更改并获得结果的简单但可行的示例:

# 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

关于powershell - 将 "native"对象传递给后台作业,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15382728/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com