[CmdletBinding()] param( [Parameter(Mandatory = $true)] [string]$TaskName, [int]$MaxAgeHours = 26, [switch]$Json ) $ErrorActionPreference = 'Stop' $task = Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue if ($null -eq $task) { if ($Json) { [pscustomobject]@{ Ok = $false; Task = $TaskName; Message = 'Task not found' } | ConvertTo-Json } else { Write-Host "Task not found: $TaskName" } exit 2 } $info = Get-ScheduledTaskInfo -TaskName $TaskName -ErrorAction Stop $lastRun = $info.LastRunTime $ageHours = $null $lastText = '' $nextText = '' if ($lastRun -and $lastRun.Year -gt 1900) { $ageHours = [math]::Round(((Get-Date) - $lastRun).TotalHours, 1) $lastText = $lastRun.ToString('yyyy-MM-dd HH:mm:ss') } if ($info.NextRunTime) { $nextText = $info.NextRunTime.ToString('yyyy-MM-dd HH:mm:ss') } $ok = $true $reasons = @() if ($null -eq $ageHours) { $ok = $false $reasons += 'never ran' } elseif ($ageHours -gt $MaxAgeHours) { $ok = $false $reasons += "last run $ageHours h ago" } if ($info.LastTaskResult -ne 0) { $ok = $false $reasons += "last result $($info.LastTaskResult)" } $payload = [pscustomobject]@{ Ok = $ok Task = $TaskName State = [string]$task.State LastRun = $lastText AgeHours = $ageHours LastResult = $info.LastTaskResult NextRun = $nextText Reasons = ($reasons -join '; ') } if ($Json) { $payload | ConvertTo-Json -Depth 3 } else { $payload | Format-List } if (-not $ok) { exit 1 } exit 0