Search code examples
powershelljobs

Restart a completed background job in PowerShell


In PowerShell 5.1 I have created a background job with the below command

Start-Job { while($true) { Get-Random; Start-Sleep 5 } } -Name Sleeper

The job gets created fine and it returns the results with Receive-Job as well. And I stopped it with Stop-Job cmdlet.

And I would like to restart it again in the same PS session.

I execute Get-Job cmdlet and I see the job there in the Stopped state.

How to restart it without recreating it?

I could not get this information in about_Jobs.

The script block is just a sample script. I am more interested to know if there is a way to restart the already existing job.


Solution

  • You cannot re-run completed jobs. One thing you could do is start a new job from the command of the completed one:

    $j1 = Start-Job -ScriptBlock { ... }
    ...
    $j2 = Start-Job -ScriptBlock ([scriptblock]::Create($j1.Command))
    

    If you need something that you can re-run at will you probably want a scheduled task or a scheduled job:

    $trigger = New-JobTrigger -Daily -At '2:00 PM'
    $options = New-ScheduledJobOption -StartIfOnBattery -StartIfIdle
    Register-ScheduledJob -Name 'myjob' -ScriptBlock { ... } -Trigger $trigger -ScheduledJobOption $options
    

    and (re-)invoke it e.g. like this:

    (Get-ScheduledJob -Name 'myjob').StartJob()