Powershell Start-Job not working from scheduled task

I had a powershell script that used the start-job command to pass some variables to another script that would run in the background.

I was using start-job as i was passing an array as one of the parameters to the second script and calling powershell.exe and passing an array did just not work (someone may be able to confirm if that is expected behavior).

The job worked properly when running from the powershell ISE but did not have the desired effect when running from a scheduled task. The start-job command never seemed to kick in and the parent job ended after a few seconds.

</pre>
start-job D:\scripts\myscripts.ps1 -args (,$my_arr), $my_var

It seems that when a scheduled task is executed and the parent script has effectively finished, any child processes that were started with the start-job command are also terminated.

My way around this was to adjust my code as follows;

$job_result = start-job D:\scripts\myscript.ps1 -args (,$my_arr), $my_var

$job_id = $job_result.id
while ($job_result.state -match "running"){
Start-Sleep -seconds 20
$job_result = get-job $job_id
}

When start-job is run it creates an object that represents the child job. By checking every 20 seconds that it was still running my parent job remained alive.

There is clearly more that could be done to handle different states and of course depending on what is happening 20 seconds might be too short or too long a time period to re-test but in this case it was sufficient.

Leave a comment