13

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

5 Answers 5

15

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.

Sign up to request clarification or add additional context in comments.

18 Comments

If I use -Command do I have to still run with start program/script: Powershell?
I tried using start program/script of both Cmd and Powershell. When I use Cmd with what you're showing for my case/added arguments, and run it, the task is hanging and doesn't finish in a normal time so I had to terminate it. When I use PowerShell, like I had before, it finishes with normal events in taskScheduler in a normal time but there's no failure exit code.
Yes. Your Program/Script is still PowerShell.exe you simply are changing the Arguments to use -Command .
Some great info here. Note that you can make -File report an exit code, but only if the script invoked explicitly uses exit <n> to exit the script. Also note that a script may fail due to PowerShell-native commands failing, which won't be reflected in $LASTEXITCODE. 0x1 which is hexadecimal 0x80070001 is a bit confusing: more accurately, the task-execution engine reports non-zero exit codes by bit-oring them with 0x80070000; to get the embedded exit code, use 2147942401 -band -bnot 0x80070000 or, conversely, 1 -bor 0x80070000L
I'm glad you found a workaround, @Michele, but just to clarify: The Last Run Result column should show (0x63) if the exit code was 99. If it is showing (0x1), perhaps you ran your script with -Command instead of -File or your script currently uses exit 1. You can only select standard fields as display columns, and ResultCode is not a standard field; it is embedded in event-instance-specific custom event data associated with event 201.
|
1

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]

Comments

1

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.

Comments

0

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     :

Comments

-1

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

1 Comment

This answer doesn't seem to have any relevance to the question...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.