FFS: Scheduled Task - Powershell, Event log, and Email alert

Discuss new features and functions
Posts: 2
Joined: 18 Apr 2017

nicbawt

I wanted my FFS tasks to write to the event log as well as send an email if a task was not successful. All the solutions I found were either overly complex, not complete, or required another 3rd party tool. I also wanted to do it all in Powershell. I'm posting my PS script here to hopefully help others save time. Just modify the variables to your liking and schedule the task.

A few notes:
1. To get the event logging to work, you need to add the source you are going to use. In my case I use source "FFS". Just run the following at an administrative PS prompt: New-EventLog -LogName Application -Source "FFS"

2. Depending on your smtp server setup, you may need to add/modify to suit your environment. Just look up the cmdlet reference for Send-MailMessage.

3. I point my PS script at a FFS_batch that I keep in the same C:\BAT\ directory. I like having that external to the script just in case i need to modify anything in the FFS setup. Drive locations, version changes, filters, etc... It's much easier in the GUI.

4. In your scheduled task Action:
Program/script= Powershell.exe
Arguments= -file "C:\bat\NameOfYourFFSBatch.ffs_batch"

5. My Powershell kung fu is weak. I'm sure others can clean this up or do better. Just hoping to help.

Enjoy.
#FFS powershell with eventlog and email alert when script errors.
#Edited 04/17/17
$recipient = 'you@somedomain.com'
$sender = 'FFSALERT@somedomain.com'
$batch = 'TheNameOfYourFFSBatch.ffs_batch'
$folder = 'C:\BAT\'
$hostname = hostname
$smtpserver = 'smtp.server.com'

#Shouldn't need to modify anything below this.

#Runs the defined ffs_batch. Waits for it to finish. Returns true when finished. Returns the exitcode/returncode.
$ffs = Start-Process "C:\Program Files\FreeFileSync\FreeFileSync.exe" "$folder$batch" -wait -PassThru
$ffs.HasExited
$ffs.exitcode

<#
FFS Return Codes
0 - Synchronization completed successfully
1 - Synchronization completed with warnings
2 - Synchronization completed with errors
3 - Synchronization was aborted
#>

#If return code (exitcode) = 0 (success) write event log only. If any other code returned, write event log and send email.
#You have to add the event source before a log can successfully be created: New-EventLog -LogName Application -Source "FFS"
if ($ffs.exitcode -like "0")
    {Write-EventLog -LogName Application -Source "FFS" -EventId 1234 -Message "$batch completed without error."}
    else {Write-EventLog -LogName Application -Source "FFS" -EventId 4321 -Message "$batch completed WITH error or warnings." ;
            Send-MailMessage -To $recipient -From $sender -Subject "$batch on $hostname Has an error or warning" -SmtpServer $smtpserver}
User avatar
Site Admin
Posts: 7211
Joined: 9 Dec 2007

Zenju

Email notifications are now directly supported with FreeFileSync 10.20!