3

I am starting several jobs (with Start-Job) and at the end of my script i do a check to see if the jobs have been running more than X seconds. I would then like to take the Running and Failed jobs and restart them until they succeed.

The jobs are named after the server that I'd like to run against (with for example Test-Connection). My problem is that I can't figure out how to re-submit the jobs!

get-job | where { $_.state -eq "running" } | remove-job -force | start-job -ScriptBlock { echo $_ }
  • How can I pipe the Name of the failed/hanged job(s) to the new job I am starting?
  • How can i wait for the remove-job to finish before I continue on Start-Job?

Kind regards:)

Sune
  • 3,080
  • 16
  • 53
  • 64

1 Answers1

3

One way to restart failed jobs:

Start-Job -Name Foo -ScriptBlock {
    $ErrorActionPreference = 'Stop'
    Get-Item C:\DoesNotExists 
} | Wait-Job > $null

Get-Job | ? { $_.State -eq 'Failed' } | % {
    Start-Job -Name $_.Name -ScriptBlock { iex $args[0] } -ArgumentList $_.Command | Wait-Job | Receive-Job
}
Andy Arismendi
  • 50,577
  • 16
  • 107
  • 124
  • Ahh! I don't have to worry about removing the failed jobs ofcourse! What does the IEX do? Is that how i resubmit with the same name? – Sune Mar 17 '12 at 00:11
  • 1
    @Sune `iex` is an alias for `Invoke-Expression`. The scriptblock text of the failed job is passed to the new job as a string. `Invoke-Expression` is being used to treat the string as a command. I updated it to show you how you can reuse the job name. – Andy Arismendi Mar 17 '12 at 00:20