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

Michele picture Michele · Dec 21, 2018 · Viewed 8.5k times · Source

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

Answer

HAL9256 picture HAL9256 · Dec 21, 2018

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.