Setting Up A Scheduled Batch Job That Notifies Me in Email When Finished

I have a batch job scheduled to run every night that could take several hours to finish. It’s just a simple data copy job with a set of robocopy commands but I have no way of knowing how it went during the night. It would be nice if the job can notify me the status of the job in an email, preferably having a log file attached.

Since PowerShell has a native cmdlet Send-MailMessage that can be easily set up and use, why not taking advantage of it?

Firstly, I switched the .bat batch file into a PowerShell script, save as .ps1 file and added two Send-MailMessage cmdlets to send two notification emails, one at the beginning of the job and one at the end of the job. In the one sent at the end of the job, I also included the task status code using Get-ScheduledTaskInfo cmdlet so I can tell whether the task is finished successfully or not.

The final script looks like this:

$log = "z:\onedrive\mcqh\datasync.log"

$body = "Daily data sync job has started on $(Get-Date)"
Send-MailMessage -To "[email protected]" -From "[email protected]" -SMTPServer 192.168.37.8 -Subject "Daily Backup Sync Started" -Body $body

robocopy source target /s /mir /np /log:$log
robocopy source target /s /mir /np /log+:$log

$body = "Daily data sync job has successfully ended on $(Get-Date) with status code " + (get-scheduledtaskinfo -taskname "Sync Backup").LastTaskResult
Send-MailMessage -To "[email protected]" -From "[email protected]" -SMTPServer 192.168.37.8 -Subject "Daily Backup Sync Ended" -Body $body -Attachments $log

Secondly, I changed the scheduled job in Task Scheduler and edited the Action to use PowerShell to launch the script.

Edit Action - PowerShell

Manually ran the job and it worked like a charm.

2 thoughts on “Setting Up A Scheduled Batch Job That Notifies Me in Email When Finished

  1. Hi,

    I need a powershell script that can do a search on AD to pick out those user accounts that will be expired in 2 weeks, and send an email to inform the respective managers. The search should be base on a particular OU only, not the whole main domain. Have you done anything like this before?

    thanks,
    Paul

    1. Yes, it’s totally doable. If you plan on running the script on your workstation, make sure the AD powershell module is installed.

Leave a Reply

Your email address will not be published. Required fields are marked *