How can I detect and restart a stalled PowerShell task?

0
0
Asked By RogueIT_47 On

I have a PowerShell job that starts through Task Scheduler at 9:30 AM and runs until the monitored jobs indicate that it should stop later in the evening. On some days, the script gets stuck and stops making progress. What is the best way to detect that stall and restart the scheduled task? I was considering a second task that runs every 15 minutes and checks the transcript's last write time, but I'm open to a cleaner or more reliable approach.

4 Answers

Answered By CedarMosaic8 On

Task Scheduler already has settings that may handle this without a separate watcher script. Set “Stop the task if it runs longer than” to a reasonable limit, then configure “If the task fails, restart every” with the retry interval and maximum attempts you want. Also enable transcription or other logging so you can investigate what caused the stall.

Answered By PixelHarbor3 On

The most reliable fix is to identify why the job hangs and make it fail cleanly. Since this is a web-scraping job, add timeouts around network requests—Invoke-WebRequest supports a timeout setting—so a slow or unreachable site does not leave the script waiting indefinitely. Use try/catch logging and exit with a failure code so Task Scheduler can restart it.

RogueIT_47 -

It’s a web-scraping job that occasionally gets stuck waiting on something, so adding a timeout to Invoke-WebRequest sounds like a good place to start.

Answered By MapleCircuit21 On

A heartbeat is usually better than watching transcript timestamps. Have the script update a small heartbeat file or timestamp after each successful unit of work, or every few minutes while it is healthy. A second scheduled task can check whether the heartbeat is older than the allowed threshold, stop the original task, and start it again. Just make sure the restart logic prevents multiple copies from running at once.

Answered By QuietOrbit6 On

You can also run the main operation as a background job and monitor it from the controlling script. Use Receive-Job to collect output and Stop-Job when it exceeds a timeout, then retry until it succeeds or a maximum retry count is reached. This gives you more control than relying only on the transcript and makes it easier to record what happened.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.