PowerShell script errors and the exit code in Task Scheduler
Your PowerShell script prints red errors, but Task Scheduler shows 0x0; or every failure shows up as 0x1 whatever the script returned. Both come from how powershell.exe turns a script's errors into an exit code. Once you know the rules, the real result is easy to report.
How PowerShell decides the exit code
Microsoft's documentation for powershell.exe (Windows PowerShell 5.1) and pwsh (PowerShell 7) describes two ways to start a script, and they behave differently:
-File script.ps1: the exit code is the number you pass toexit. If the script ends normally, it is 0. If a terminating error (athrow, or a cmdlet run with-ErrorAction Stop) isn't caught, it is 1.-Command "…": the exit code is 0 or 1, from whether the last command succeeded ($?), unless you callexit. Any other code, for example 3 from a program you ran, is squashed to 1. Microsoft suggests ending withexit $LASTEXITCODEto keep it.
The trap is the third kind of error. Most cmdlet failures are non-terminating: Copy-Item on a missing file, Invoke-Sqlcmd with a bad query or Write-Error print a red message and the script carries on. With -File, a script that had ten of those still exits with 0, and Task Scheduler shows 0x0.
Native programs add one more rule: when your script runs an .exe, its exit code is in $LASTEXITCODE, and a failing program does not stop the script unless you check it.
Make the script fail properly
At the top of the script, turn every error into a terminating one, and check native programs explicitly:
$ErrorActionPreference = 'Stop' # every cmdlet error now stops the script (exit code 1 with -File)
& C:\tools\export.exe --day today
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
Start it with -File, not -Command, so the code you pass to exit survives.
Report the result to TaskBeacon
Now the exit code is honest, but someone still has to look at Task Scheduler. The wrapper below runs any program, including powershell.exe -File your-script.ps1, and sends its exit code to TaskBeacon: /0 is OK, anything else a failure, together with the last 20 lines of output.
# 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 tooIn the app, the Code tab of your job gives you this code with the job's own address instead of your-job-id, and you can untick the parts you don't need.
For a PowerShell script, the task's arguments become -NoProfile -ExecutionPolicy Bypass -File C:\jobs\taskbeacon-run.ps1 powershell.exe -NoProfile -File C:\jobs\nightly.ps1. The wrapper ends with the same exit code, so Task Scheduler agrees with TaskBeacon.
Some scripts can't be changed and print errors while exiting with 0. For those, send the output with the finishing ping and add an output rule such as Fail if the output contains ERROR, Exception; see Words in the output.
What you get
- Failed with the exit code and the end of the output, by email, Slack, Teams or a webhook.
- Missed when the task didn't run by its planned time plus grace, which no exit code can tell you.
- Late when the script is still running long after its usual duration, for example stuck on a prompt such as
Read-Hostor a confirmation that nobody can answer.
Without TaskBeacon
Use $ErrorActionPreference = 'Stop', -File and explicit exit codes as above, wrap the body in try { … } catch { …; exit 1 }, and send yourself a message from the catch block with a mail library or a Teams Workflows webhook. That catches errors inside the script. Runs that never start, and scripts that hang, still need something outside the machine that expects a signal; see a scheduled job that didn't run.
Connected Claude or ChatGPT to TaskBeacon? Ask it "what failed last night, and why?" and it answers from your jobs. How that works.
Related
In the Docs: PowerShell (Task Scheduler) · Exit code in the ping · Words in the output.
- Task Scheduler Last Run Result 0x0, but the script failedLast Run Result 0x0 only means the program it started returned 0.
- Task Scheduler can't send email any more: get an alert when a task failsThe built-in e-mail action is gone; event-triggered tasks miss runs that never happened.
- SQL Server Agent job failure alerts without Database MailAgent emails need Database Mail, an operator and a restart, and say nothing about a job that didn't run.
TaskBeacon is free to start, with every feature open for now and no credit card. Create a job, paste the code, and the first ping shows up on the job page.
Start free View live demoSources
- Microsoft Learn: about_PowerShell_exe (Windows PowerShell 5.1, exit codes for -File and -Command) (2024-07-23)
- Microsoft Learn: about_Pwsh (PowerShell 7.5) (2026-01-18)
- Microsoft Learn: about_Automatic_Variables ($LASTEXITCODE) (2026-04-02)
- Microsoft Q&A: Getting PowerShell return code 2147942401 (2022-12-27, old: a sign of demand)
Page checked against its sources on 2026-11-09. Menus and limits of other products change; if something here no longer matches, write to support@taskbeacon.io.