Passing “native” object to background jobs

前端 未结 2 1908
盖世英雄少女心
盖世英雄少女心 2020-12-19 02:11

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 pa

2条回答
  •  隐瞒了意图╮
    2020-12-19 03:04

    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
    

提交回复
热议问题