title: How get task scheduler to detect failed error code from powershell script
body: <p>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.</p>
  
  <p>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).</p>
  
  <pre><code>$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
  </code></pre>
  
  <p>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.  </p>
  
  <p>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.</p>
  
  <p>I've been looking at <a href="https://stackoverflow.com/questions/53875089/how-check-for-errors-with-powershell-sql?noredirect=1#comment94619598_53875089">powershell errors sql</a>, <a href="https://docs.microsoft.com/en-us/windows/desktop/TaskSchd/task-scheduler-error-and-success-constants" rel="noreferrer">task scheduler success error</a>, <a href="https://docs.microsoft.com/en-us/windows/desktop/TaskSchd/task-scheduler-error-and-success-constants" rel="noreferrer">tips tricks scheduled tasks</a>, <a href="https://stackoverflow.com/questions/11647870/capturing-in-powershell-different-sqlcmd-exitcode-for-connectivity-data-issues">powershell exit code</a>, but it's not helping.</p>
  
  <p>The powershell scripts are set up in task scheduler like this:</p>
  
  <p><strong>action:</strong> start a program</p>
  
  <p><strong>program/script:</strong> PowerShell</p>
  
  <p><strong>Add arguments:</strong> -ExecutionPolicy Bypass -File C:\Users\me\Documents\powershell\disasterBackup.ps1</p>