I was recently looking at reporting the status of scheduled tasks to Nagios, where the requirements were as follows:
- Return scheduled tasks that have run successfully in the previous day with status ‘OK’
- Return scheduled tasks that have not run succesfully or tasks where the last run time was before the previous day with the status ‘Critical’
This had me thinking of how to compile a script with allow for the flexibility to specify mandatory functions for the task name and for the number of days since the scheduled task was last run, as I would like to report the status of tasks to which were not configured to be triggered on a daily schedule.
Firstly, I needed to specify the mandatory parameters I required to use within the script for the task name and number of days since the task was last run:
Param ([parameter(Mandatory = $true)][string] $TaskName,[parameter(Mandatory = $true)][string] $Days)
Now, we need to query the schedule service, as the script will always run agaisnt the local machine, we will use the DNS.GetHostName method to as the connection string to the schedule service and then filter the returned scheduled tasks using the task name parameter specified.
$Schedule = New-Object -Com("Schedule.Service") $Schedule.Connect([System.Net.Dns]::GetHostName()) $Task = $Schedule.GetFolder("\").GetTasks(0)|Where-Object{$_.Name -eq $TaskName}
As per my requirements I now need to generate the return codes to be used for the service status. For the service status to be returned as OK i require the LastRunTime to be less than the number of days specified in the mandatory Days parameters and also for the LastTaskResult code to be equal to 0.
If ($Task.LastRunTime -gt (get-date).AddDays(-$Days) -and $Task.LastTaskResult -eq "0") { $returncode = 0 }
The critical status needs to be returned when the LastRunTime is less than the number of days specified in the mandatory Days parameter or if the LastTaskResult is not equal to 0.
If ($Task.LastRunTime -lt (get-date).AddDays(-$Days) -or $Task.LastTaskResult -ne "0") { $returncode = 2 }
Finally I want to output the service status information for the scheduled task being monitored and exit the session returning the error code:
"The Scheduled Task " + $Task.Name + " last run on " + $Task.LastRunTime + " with the Last Run Result " + $Task.LastTaskResult exit $returncode
While the script was created to be executed as an external script within Nagios, this can be run standalone from Windows Powershell. If your are looking to add external scripts to Nagios such as this one see the below link for more information;
https://deangrant.wordpress.com/2013/09/12/creating-and-running-external-scripts-within-nagios-xi/
The full Windows Powershell script can be downloaded from the below link: