2

If two background jobs are started from the same session, how can one of them determine that the other has finished? Initially I tried something like this:

$j1 = Start-Job {
    Start-Sleep -Seconds 5
    "j1 done"
}

$j2 = Start-Job {
    param($j)
    "j2 waiting..."
    $j | Wait-Job
    "j2 done"
} -ArgumentList $j1.Finished

$j1,$j2 | Receive-Job -Wait

Of course it doesn't work because $j2 only gets a serialized snapshot of $j1 (the job Status in the snapshot would never change); furthermore each background job has their own job repository so $j object appears to be bogus in the context of $j2.

The jobs can synchronize via the mutexes, filesystem (if on the same machine) or a DB, etc. but I'm wondering if powershell provides any remoting-friendly facilities for this?

Serguei
  • 2,910
  • 3
  • 24
  • 34

2 Answers2

1

I don't think that is going to work because the job objects are relative to their PowerShell session/runspace. The Start-Job cmdlet spins up a new runspace (typically a new process). I don't believe PowerShell events would work either because they also appear (according to docs) to be session specific. I would keep it simple and use a file - pass the path into both jobs.

Keith Hill
  • 194,368
  • 42
  • 353
  • 369
  • Yeah using files is OK (I used global mutexes, which I think are backed by the filesystem anyway) as long as everything's on the same machine, which is safe to assume given `Start-Job` (vs `Invoke-Command`). – Serguei Jan 16 '13 at 02:23
0

try this - in PowerShell 3.0 and newer:

$j1 = Start-Job {
    Start-Sleep -Seconds 5
    "j1 done"
}

$j2 = Start-Job {
    "j2 waiting..."
    $Using:j1 | Wait-Job
    "j2 done"
}

$j1,$j2 | Receive-Job -Wait
Ladislav
  • 320
  • 3
  • 10