Transferring a "native" object to background jobs

This is what I would like to achieve one way or another.

I have a custom assembly defining some objects. In my script, I create a custom object that I would like to pass to the script block, preserving this behavior of the object.

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 this or achieve the same effect? Thank you for your help.

+5
source share
2 answers

Instead of background jobs, you can use PowerShellwith BeginInvoke, EndInvoke. Here is a simple but working example of transferring a living object to a “task”, changing it, and obtaining 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
+7
source

PowerShell , , . / , .

, - / -ArgumentList .

:

Start-Job {
    param ($ConstructorArguments)
    Add-Type -AssemblyName MyCustomDll
    $object = New-Object MyCustomDll.MyCustomObject $ConstructorArguments
    $object | Get-Member
} -ArgumentList Foo, Bar | Wait-Job | Receive-Job 
+4

All Articles