Alert when a Windows scheduled task fails
Task Scheduler records a failed run in the task's history, but tells no one. There is no action for a failed task, so the script reports the failure itself — to your Telegram, Discord or Pushover.
You need a BugsRadar project with a channel and the project's API key: see the quick start.
A function for all scripts
Put the call into one file and load it from every task script:
function Send-BugsRadar {
param(
[Parameter(Mandatory)] [string] $Message,
[string] $Level = 'error',
[string] $Category = 'Task Scheduler'
)
# Windows PowerShell 5.1 doesn't always use TLS 1.2 by itself
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
$uri = 'https://api.bugsradar.com/api/v3/notify?level={0}&category={1}&host={2}' -f `
$Level, [Uri]::EscapeDataString($Category), [Uri]::EscapeDataString($env:COMPUTERNAME)
Invoke-RestMethod -Method Post -Uri $uri -Headers @{ 'X-Api-Key' = $env:BUGSRADAR_KEY } `
-ContentType 'text/plain; charset=utf-8' -Body $Message | Out-Null
}
Report a failure
$ErrorActionPreference = 'Stop' turns every PowerShell error into one that catch sees. A program that exits with an error code doesn't throw, so its $LASTEXITCODE is checked by hand:
. C:\Scripts\Send-BugsRadar.ps1
$ErrorActionPreference = 'Stop'
try {
& C:\Tools\report.exe --daily
if ($LASTEXITCODE -ne 0) { throw "report.exe exited with code $LASTEXITCODE" }
}
catch {
Send-BugsRadar -Message ('Nightly report failed: ' + $_.Exception.Message)
exit 1
}
exit 1 keeps the failure in the task's Last Run Result.
Set up the task
- In Task Scheduler, create a task and choose Run whether user is logged on or not.
- On the Actions tab, add Start a program: program
powershell.exe, arguments-NoProfile -ExecutionPolicy Bypass -File C:\Scripts\nightly-report.ps1. - Give the account the task runs as an environment variable
BUGSRADAR_KEYwith your project's API key. Or write the key intoSend-BugsRadar.ps1and let only that account and administrators read the file.
Programs and batch files
When the task starts a program rather than a script, || in a command line runs curl only if the program exits with an error. curl.exe comes with Windows 10 version 1803, Windows Server 2019 and later:
@echo off
C:\Tools\export.exe --all || curl.exe -fsS --max-time 15 -H "X-Api-Key: %BUGSRADAR_KEY%" --data-binary "Export failed on %COMPUTERNAME%" "https://api.bugsradar.com/api/v3/notify?category=Task+Scheduler"
Test it
Send a test message from a PowerShell window:
. C:\Scripts\Send-BugsRadar.ps1
Send-BugsRadar -Message 'Test alert from Task Scheduler' -Level information
Then run the task itself with Run in Task Scheduler and check Last Run Result.