Windows task scheduler email notification

scheduled-taskwindows-server-2003

I am using the Windows Task Scheduler to run a executable that returns 0 when it runs successfully. However, I would like an email notification if (1)the task fails to run or (2)the return code if anything other than 0.

Is this something the Windows Task Scheduler on Windows Server 2003 can do???

Best Answer

In my quest to eradicate cmd.exe [grin], here's a Powershell script that should also work for you:

# attempt to run your exe.  iex is an alias for the invoke-expression cmd
iex c:\path_to_exe\myprog.exe

# $? lets us know if the previous command was successful or not
# $LASTEXITCODE gives us the exit code of the last Win32 exe execution
if (!$? -OR $LASTEXITCODE -gt 0) 
{
    $smtpServer = "smtp.mydomain.com"
    $fromAddress = "sender@mydomain.com"
    $toAddress = "recipient@mydomain.com"
    $subject = "FAIL"
    $msgBody = "HEY, YOU GOT PROBLEMS"

    # This block is optional depending on your SMTP server config
    # You need it if your SMTP server requires authentication
    $senderCreds = new-object System.Net.networkCredential
    $senderCreds.UserName = "senderusername"
    $senderCreds.Password = "senderpwd"

    $smtpClient = new-object Net.Mail.SmtpClient($smtpServer)
    $smtpClient.Credentials = $senderCreds
    $smtpClient.Send($fromAddress,$toAddress,$subject,$msgBody)
}