Michele
Michele

Reputation: 3871

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

Upvotes: 12

Views: 24990

Answers (5)

js2010
js2010

Reputation: 27423

If you don't want to do the bit math ($tasknum -band -bnot 0x80070000), get-scheduledtaskinfo returns a lasttaskresult property.

Get-ScheduledTaskInfo script.ps1

LastRunTime        : 10/23/2022 10:51:51 AM
LastTaskResult     : 1
NextRunTime        :
NumberOfMissedRuns : 0
TaskName           : script.ps1
TaskPath           :
PSComputerName     :

Upvotes: 0

Michele
Michele

Reputation: 3871

I know this is way after the fact, but what I wound up doing for this is that I called an email script directly from my powershell script when it has a failure case.

Upvotes: 1

Cary Sweet
Cary Sweet

Reputation: 11

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]

Upvotes: 1

Jeremy Rodriguez
Jeremy Rodriguez

Reputation: 1

What I'd do is to attach a scheduled task to the failed event so when this takes place raise the scheduled task.

Upvotes: -2

HAL9256
HAL9256

Reputation: 13453

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.

Upvotes: 14

Related Questions