The trouble with Task Scheduler is 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, clicking on the Details tab when viewing 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, to get the "Correct" Result code, you will have to find your event, and click on the Details tab, then you can find the "Correct" ResultCode to filter on.
ox1as0x80070001. I was thinking that, maybe the0x8007in the high word was the event ID; but 201, in hex is0xC9. It's like it's pulling a number out of its butt and sticking it in the high word of the result code when the exit code isn't 0. – RobH Feb 14 '24 at 17:25