How can I detect and restart a stalled PowerShell task?
Asked by
RogueIT_47
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.
Answers
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.
Reply to this answer
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.
Reply to this answer
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.
Reply to this answer
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.
Reply to this answer
Add your answer
Answers are reviewed before publication.
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.