runnin a job within a job, and getting back that data

This topic contains 1 reply, has 2 voices, and was last updated by Profile photo of Don Jones Don Jones 4 years, 1 month ago.

  • Author
    Posts
  • #4668
    Profile photo of Ian Douglas
    Ian Douglas
    Participant

    I am using remoting to execute a scriptblock on a group of servers, and using the ‘-asjob’ parameter to run it in the background. For example:

     

    1>  $job = Invoke-Command -ComputerName $ComputerName -scriptblock $ScriptBlock -jobname $JobName -throttlelimit $ThrottleLimit -AsJob

     

    Once the job has completed, I write the results and the errors into variables, eg,

     

    2>  $jobresult = Get-Job -Name $jobName |  Wait-Job | Receive-Job -ErrorVariable $ErrorVariableName -ErrorAction SilentlyContinue

     

    This works fine,  but I have to wait around for the job to finish in order to issue the above command, when it would be much better for another wrapper job to run that waits for the childjobs to complete, then writes the results into the variable $jobresult. For example, replace (2) with something like:

     

    3>  Start-Job -Name JobExec -ScriptBlock { $jobresult = $job | Wait-Job | Receive-Job -ErrorVariable $errorVariableName -ErrorAction SilentlyContinue}

     

    If I issue 1 & 3 above, everything executes, but there’s no data written into $jobresult  ( at least not that I can get out) or $errorVariableName . Is there something I’m missing with variable scoping here? Something else I'm missing altogether? I’ve tried forcing $jobresult to have global scope, with no luck. Please advise!

    I want to be able to run 1 and 3 together in the background, and when they are done, both $jobresult and $errorVariable will be populated with data, and in the meantime I'm free to use the console, without having to wait to issue the receive-job

  • #4676
    Profile photo of Don Jones
    Don Jones
    Keymaster

    Been watching Inception, have we?

    Do this in a script. In between your 1 & 2 commands, put Wait-Job. Have it wait until all jobs complete. Then, just run the script as a job. I'm curious to see if that makes a difference.

    I need to spend a sec further unwinding the syntax and its implications, but the nesty-job is the oddness.

You must be logged in to reply to this topic.