We (our company) are runnning several scheduled tasks on a server. Recently some of the tasks started to fail on running. We'd like to query all the scheduled jobs reporting anyone whose last run result isn't 0x0 using powershell.
I've tried a lot of research for finding an easy way to do so, but only found scripts, that can query scheduled task by name (only to check one single task) but not by last run result. It wouldn't be helpful to add a new codeline for every newly intstalled scheduled task.
There is a quite similar entry on that topic, but as described above with the task name as parameter. (How to send email when SPECIFIC scheduled task fails to run)
$ScheduledTaskName = "Taskname"
$Result = (schtasks /query /FO LIST /V /TN $ScheduledTaskName | findstr "Result")
$Result = $Result.substring(12)
$Code = $Result.trim()
If ($Code -gt 0) {
$User = "admin@company.com"
$Pass = ConvertTo-SecureString -String "myPassword" -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential $User, $Pass
$From = "Alert Scheduled Task <task@servername>"
$To = "Admin <admin@company.com>"
$Subject = "Scheduled task 'Taskname' failed on SRV-001"
$Body = "Error code: $Code"
$SMTPServer = "smtp.company.com"
$SMTPPort = "25"
Send-MailMessage -From $From -to $To -Subject $Subject `
-Body $Body -SmtpServer $SMTPServer -port $SMTPPort -UseSsl `
-Credential $Cred
}
The code should be something like that, I guess
Get-ScheduledTask | where LastTaskResult -NE "0x0"