Ping CronMissed from PowerShell

On this page

On Windows a scheduled task usually runs a PowerShell script. Invoke-RestMethod sends the ping, a try and catch block keeps a failed ping from failing the script, and the exit code of the last program becomes the signal.

What should a PowerShell job send?

  • A request to /start before the work, so CronMissed can time the run and notice a job that never finishes.
  • A request to the plain URL when the work succeeded, or to /fail when it did not. /<exit status> works too: 0 is a success and any other number is a failure.
  • The end of the output in the request body, up to 100,000 bytes, so the alert shows the error without a trip to the server.

What is the script?

ping.ps1
param([string]$PingUrl = $env:CRONMISSED_PING_URL)

function Send-Ping([string]$Suffix = '', [string]$Body = $null) {
    try {
        if ($Body) { Invoke-RestMethod -Uri "$PingUrl$Suffix" -Method Post -Body $Body -TimeoutSec 10 | Out-Null }
        else { Invoke-RestMethod -Uri "$PingUrl$Suffix" -TimeoutSec 10 | Out-Null }
    } catch { }   # a lost ping must never break the job
}

Send-Ping '/start'
try {
    $output = & "C:\Tools\export.exe" 2>&1 | Out-String
    $status = $LASTEXITCODE
} catch {
    $output = $_ | Out-String
    $status = 1
}
$tail = if ($output.Length -gt 100000) { $output.Substring($output.Length - 100000) } else { $output }
Send-Ping "/$status" $tail
exit $status

Keep the ping URL in an environment variable or a secret store, never in a public repository: the URL is the check's only credential.

How do I run it from Task Scheduler?

Register a task whose action is powershell.exe -NoProfile -File C:\Tools\ping.ps1, and choose the account it runs as. The Windows Task Scheduler guide lists the options that decide whether it runs when nobody is logged on.

Sources

Questions and answers

Why use $LASTEXITCODE?
It holds the exit status of the last native program the script ran. Cmdlets set $? instead, so for a cmdlet job use try and catch and set the status yourself.
Does it work in PowerShell 7 and Windows PowerShell?
Both have Invoke-RestMethod with -TimeoutSec, so the script runs on either.
Create the check these snippets report to

Make a check, copy its ping URL into the snippet, and run the job once.

Start monitoring