powershellscheduled-tasks

How to pass Powershell script error to Task Scheduler


I‘m running a Windows PC in an environment with quite some power failures. It therefore needs to send me an email every time it has rebooted. I have implemented a task in the task scheduler that is triggered by system start. This task executes a Powershell script that includes a „Send-MailMessage“ instruction. This in principle works well e.g. after a Windows update triggered reboot. However if there is a power failure and the network infrastructure takes longer to recover than booting up the PC I don‘t get any email. Even I have set in the settings of my task scheduler task the switch that the task should be repeated every 5 minutes in case that it fails, I don‘t get any email. My question is: how is the failure of an instruction like „Send-MailMessage“ within a Powershell script passed to the Task Scheduler that obviously not seem to start the task a second or third time.

If I run my script in a shell simulating that it can’t connect to the email server, e.g. by using a wrong smtp server address, the script exist with the usual failure messages. If I use this modified script in Task Scheduler, it shows after a reboot that the process was executed successfully.

What is the correct mechanism to pass an error on so that task scheduler knows that something went wrong and it would fire up a second or third try until the network is up again?


Solution

  • What'd I'd do is program the script to test the network connection before attempting to send emails. Additionally, you can add a counter and have the script EXIT 1 if it fails to ping after 5 minutes. I'd imagine that'd make the scheduled task properly re-run as well.

    do {
    $ping = test-connection google.com -count 1 -Quiet
    } until ($ping)
    Send-Mail -Something
    

    Is this what you wanted? I'll update my answer accordingly : )