Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How get task scheduler to detect failed error code from powershell script

I have a few powershell scripts that I'm trying to get to trigger as a failed state in the windows task scheduler when they have failures inside them. So I'm doing something like this inside the powershell script. I tried an exit code of 1 or 99, and it doesn't look like windows task scheduler is seeing that as a failure state. So my failure code email doesn't get sent out to notify me.

How do I get task scheduler to see that my powershell script had a failure? It always has event codes of 129 (created task process), 100 (task started), 200 (action started), 110 (task triggered), 201 (action completed), 102 (task completed).

$global:ErrorStrings = New-Object System.Collections.Generic.List[System.Object] #I add strings onto the list as I find errors

$errorCodeAsString = ""
foreach ($item in $global:ErrorStrings.Members){
   $errorCodeAsString += (" " + $item + "..")
}
if($errorCodeAsString -ne "")
{
   write-output  "Error: $errorCodeAsString"
   Exit 99 #Exit 1 didn't cause task scheduler to see error at exit either
}
Exit 0

I know my list is populated with errors because I created them to test it. I checked that the errorCode as string was a length and hit the exit 99 or 1. The task scheduler is still showing the normal event codes.

I have an email alert on failure scheduled and since the event codes aren't showing failures, it will never trigger to send my email. This is windows 10, in case it matters.

I've been looking at powershell errors sql, task scheduler success error, tips tricks scheduled tasks, powershell exit code, but it's not helping.

The powershell scripts are set up in task scheduler like this:

action: start a program

program/script: PowerShell

Add arguments: -ExecutionPolicy Bypass -File C:\Users\me\Documents\powershell\disasterBackup.ps1

like image 785
Michele Avatar asked Dec 21 '18 16:12

Michele


People also ask

How do I view failed tasks in Task Scheduler?

If you open Event Viewer and go to: Event Viewer (Local) / Applications and Services Logs / Microsoft / Windows / TaskScheduler / Optional, you will see all the Task Histories.

How do I fix error scheduler 0x41303?

There can be a couple of reasons for this error, but the most common mistake is a scheduled date in the past. When you schedule a new task you must make sure that the start date is in the future. So to fix the error we are going to change the start date of the task.

Does PowerShell have cron?

You can also add new cron jobs with help of PowerShell. This can be handy if you need to programatically add tasks on many Windows machines.


2 Answers

HAL9256's answer did not work for me when looking for all failed tasks

When I converted his XML to search for all non-zero return codes, it ended up matching all return codes. Both zero and non-zero alike

*[EventData[Data[@Name='ResultCode'] and (Data!='0')]]

Instead, I created a task with an "on an event" trigger and the following custom xml:

<QueryList>
  <Query Id="0" Path="Microsoft-Windows-TaskScheduler/Operational">
    <Select Path="Microsoft-Windows-TaskScheduler/Operational">
      *[System[(Level=4 or Level=0) and (EventID=201)]]
        and
      *[EventData[(Data[@Name="ResultCode"]!=0)]] </Select>
  </Query>
</QueryList>

and runs the following powershell script

Send-MailMessage -To -Subject "My subject" -Body "One of the tasks failed. Please log into the server and view the event log details to find out which task failed" -SmtpServer mail.company.com -From [email protected]

like image 22
Cary Sweet Avatar answered Oct 06 '22 08:10

Cary Sweet


Part 1 is to have PowerShell return the correct Last Exit Code to Task Scheduler.

This is one of the peculiarities of Task Scheduler. It simply is reporting that, yes, PowerShell.exe ran successfully. The problem is that PowerShell.exe doesn't report back the exit code, because, yes, PowerShell.exe ran correctly, even if the script did not.

The way I have been able to get around this is to switch from running the script with the -File parameter, which doesn't return the exit value, to a -Command parameter. That way I can exit PowerShell.exe with the correct exit code by explicitly exiting with the$LASTEXITCODE value:

#Run Scheduled task with the following command

powershell.exe -Command ". C:\Scripts\RunScript.ps1; exit $LASTEXITCODE"

So in your case it would be:

powershell.exe -ExecutionPolicy Bypass -Command ". C:\Users\me\Documents\powershell\disasterBackup.ps1; exit $LASTEXITCODE"

--- Edit----

Part 2 is to have a Scheduled Task Triggering on an Event when it fails to send an email or something.

The trouble with Task Scheduler is the same thing we had with PowerShell exiting. No matter what exit code is returned, the task always logs an Event ID 201 - Action Completed... which is correct... no matter what, the task completed even if the job that was run failed internally.

Looking further into the Details of the logged Event, we can see the ResultCode in the EventData does get set correctly. So it's a simple job to filter that through the GUI right?.... well no... There is no filter beyond EventID. Now we have to write a custom Event filter to trigger on based on the ResultCode. The XML XPath query that we need is this:

<QueryList>
  <Query Id="0" Path="Microsoft-Windows-TaskScheduler/Operational">
    <Select Path="Microsoft-Windows-TaskScheduler/Operational">
      *[System[(Level=4 or Level=0) and (EventID=201)]]
        and
      *[EventData[Data[@Name='ResultCode'] and (Data='2147942401')]]</Select>
  </Query>
</QueryList>

So to break it down, we want:

Event log: Microsoft-Windows-TaskScheduler/Operational
Event Level: 4 or 0 = Information
Event ID: 201
And
Event Data: ResultCode = 2147942401

If we set the bad exit code to 1, why is ResultCode = 2147942401? because it actually returns 0x1 which is hexadecimal 0x80070001 which equals decimal 2147942401. So you will have to look at the Details of the Event to find the "Correct" ResultCode.

like image 190
HAL9256 Avatar answered Oct 06 '22 07:10

HAL9256