2

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"

1 Answers1

2

Use Get-ScheduledTaskInfo.

Get-ScheduledTask -TaskPath "\" | Where State -ne "Disabled" | Get-ScheduledTaskInfo | Where LastTaskResult -ne 0

In my example, I've just assumed you want tasks in the Task root, not any in the MS subfolders. If you store or care about tasks in the subfolders, then obviously modify the taskpath or identify the tasks you want some other way.

Get-ScheduledTaskInfo returns a bunch of properties that you can search/select. Excluding the Cim (WMI) properties, they are:

TaskName,TaskPath,LastRunTime,LastTaskResult,NextRunTime,NumberofMissedRuns
LeeM
  • 1,118
  • 8
  • 18