PowerShell (Task Scheduler)
A PowerShell wrapper around any program: it reports by the program's exit code. The program's output is kept in a temporary file; on a failure its last 20 lines go with the alert.
The code
This is the code the Code tab generates (with start and errors ticked). In the app it already contains your job's own address.
# Save as C:\jobs\taskbeacon-run.ps1
# Task Scheduler > Action: Start a program
# Program: powershell.exe
# Arguments: -NoProfile -ExecutionPolicy Bypass -File C:\jobs\taskbeacon-run.ps1 "C:\path\to\program.exe" "arg1" "arg2"
# Runs the program, then reports success or failure from its exit code.
# A .ps1 script as the program is run with powershell.exe -NoProfile -ExecutionPolicy Bypass -File script.ps1
# (an execution policy set by Group Policy still wins over Bypass).
$tb = "https://taskbeacon.io/ping/your-job-id"
$program, $programArgs = $args
# a .ps1 file is not a program Windows can start on its own ("not a valid Win32 application")
if ($program -match '\.ps1$') {
$programArgs = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $program) + @($programArgs | Where-Object { $null -ne $_ })
$program = 'powershell.exe'
}
function Send-TaskBeacon($path, $text) {
$send = @{ UseBasicParsing = $true; TimeoutSec = 10; Uri = ($tb + $path) }
if ($text) { $send.Method = 'Post'; $send.ContentType = 'text/plain; charset=utf-8'; $send.Body = [Text.Encoding]::UTF8.GetBytes($text) }
try { Invoke-WebRequest @send | Out-Null }
catch { Write-Host "TaskBeacon ping failed: $_" }
}
Send-TaskBeacon "/start"
# keep arguments that contain spaces together
$argLine = ($programArgs | ForEach-Object { if ($_ -eq '' -or $_ -match '[\s"]') { '"' + ($_ -replace '"', '\"') + '"' } else { $_ } }) -join ' '
# Windows PowerShell 5.1 refuses an empty -ArgumentList: pass it only when there are arguments
$run = @{ FilePath = $program; Wait = $true; PassThru = $true; NoNewWindow = $true; ErrorAction = 'Stop' }
if ($argLine) { $run.ArgumentList = $argLine }
# the program's output goes to temporary files: shown below, and its last 20 lines go with a failure
$out = [IO.Path]::GetTempFileName(); $err = [IO.Path]::GetTempFileName()
$run.RedirectStandardOutput = $out; $run.RedirectStandardError = $err
$code = 1
$note = ''
try {
$p = Start-Process @run
if ($null -ne $p.ExitCode) { $code = $p.ExitCode }
} catch { $note = "Could not start ${program}: $_"; Write-Host $note }
Get-Content -LiteralPath $out, $err -ErrorAction SilentlyContinue
$tail = ''
if ($code -ne 0) {
$lines = @(Get-Content -LiteralPath $out, $err -Tail 20 -ErrorAction SilentlyContinue) + @($note)
$tail = ($lines | Where-Object { $_ } | ForEach-Object { if ($_.Length -gt 300) { $_.Substring(0, 300) } else { $_ } }) -join "`n"
}
# the exit code goes at the end of the address: /0 = OK, any other number = failed
Send-TaskBeacon "/$code" $tail
Remove-Item -LiteralPath $out, $err -ErrorAction SilentlyContinue
exit $code # not 0 when it failed, so Task Scheduler shows the failure tooHow it works
The wrapper pings /start when the program begins and, when it ends, the address with its exit code at the end: /0 is OK, any other number a failure, sent with the last 20 lines of output. It sends no row count.
Untick options on the Code tab to leave parts out; untick Send output lines to send no output, only the error or exit code. See what can be reported.
Create the task from the command line
Save the script above as C:\jobs\taskbeacon-run.ps1, then create a task that runs it with your program (one line, in a Command Prompt):
schtasks /Create /TN "Nightly export" /SC DAILY /ST 02:00 /TR "powershell.exe -NoProfile -ExecutionPolicy Bypass -File C:\jobs\taskbeacon-run.ps1 C:\jobs\export.exe"
The wrapper starts the program, waits for it, and reports the result with its exit code in the address (/0 is OK, /1 or any other number a failure), with the last 20 lines of output when it failed. It ends with the same exit code, so Task Scheduler's Last Run Result agrees with TaskBeacon.
A PowerShell script as the job. Give the wrapper the .ps1 file as the program; it runs it with powershell.exe -NoProfile -ExecutionPolicy Bypass -File script.ps1 itself (Windows can't start a .ps1 on its own: %1 is not a valid Win32 application):
schtasks /Create /TN "Nightly cleanup" /SC DAILY /ST 03:00 /TR "powershell.exe -NoProfile -ExecutionPolicy Bypass -File C:\jobs\taskbeacon-run.ps1 C:\jobs\cleanup.ps1"
To wrap an existing task, open it in Task Scheduler → Actions → Edit: Program powershell.exe, Arguments as in the comment at the top of the script, with your program's path and arguments at the end.
Why the exit code lies
Task Scheduler only knows the exit code of the program it started. Three things fool it:
- A wrapper that hides it. A
.batfile ends with the code of its last command, so a failing program followed by a successfulcopyshows0x0. - A program that always returns 0. Stata in batch mode and many in-house tools exit with 0 after an error. Use the language's own code on TaskBeacon (Stata, R, Python …), which reports the error from inside.
- No run at all. When the PC is off, asleep, or the task's password expired, there is no exit code and no notice. TaskBeacon shows the job as Missed.
Common Last Run Result values: 0x0 success, 0x1 the program returned 1 (often a generic error), 0x41301 the task is still running, 0x41303 it has not run yet.
Report a number
A wrapper only sees the exit code. To send a row count, use the code for your program's own language, or ping from the program itself with ?rows=.
Common problems
- Runs by hand, not on schedule. Tick Run whether user is logged on or not, and use UNC paths instead of mapped drive letters.
- "running scripts is disabled on this system". Keep
-ExecutionPolicy Bypassin the arguments; it applies only to this run. An execution policy set by Group Policy wins over it: check withGet-ExecutionPolicy -List, and if MachinePolicy or UserPolicy is set, ask IT. - "%1 is not a valid Win32 application". A
.ps1was started as a program. Use the wrapper (it handles a .ps1), or start it aspowershell.exe -NoProfile -ExecutionPolicy Bypass -File script.ps1. - A path with spaces. Put it in quotes in the task's arguments:
"C:\Program Files\Tool\tool.exe".
Use cases: Task Scheduler Last Run Result 0x0, but the script failed · Task Scheduler can't send email any more: get an alert when a task fails · PowerShell script errors and the exit code in Task Scheduler. More questions: FAQ.