-1

I have script for our monitoring software and i would like to monitor failed or succesfull windows scheduled task.

Powershell script looks like this:

#Monitor windows tasks for checkmk raw 1.6.0
#Last update: 31.05.2021

$tasks = Get-ScheduledTask | Get-ScheduledTaskInfo | Select TaskName,LastRunTime,LastTaskResult

#CHECKMK states
#$OK = "0 MWT -"
#$Warning = "1 MWT -"
#$Crit = "2 MWT -"
#$Unknown = "3 MWT -"

$incre

foreach($task in $tasks)
{
    if($($task.LastTaskResult) -eq 0){
        $incre++
        Write-Host "0 MWT$incre - Scheduled task: $($task.TaskName) was succesfull"
    }
    else{
        $incre++
        Write-Host "2 MWT$incre - Scheduled task: $($task.TaskName) has failed."
    }
}

Clear-Variable -Name "incre"

Output of script is this:

2 MWT1 - Scheduled task: ftp has failed.
0 MWT2 - Scheduled task: Optimize Start Menu Cache Files-S-1-5-21-3586077036-2416152140-2432273966-1104 was succesfull
0 MWT3 - Scheduled task: Adobe Acrobat Update Task was succesfull
0 MWT4 - Scheduled task: FSRM_Update was succesfull

Each line adds service to our monitoring software. It needs to have different names thats why i incrementing value for each line MWT1,2,3.

Problem is, i need to have same incremented value for each object everytime script is run. And it needs to be dynamic, when i add task its gonna give it numbers which were never use before and they will stick with it and when i remove task it will remove that number and will never be used again or it will used only for newly created tasks.

Is it somehow possible?

Johny Wave
  • 111
  • 2
  • 11

1 Answers1

0

If I understand correctly, why not add a calculated property to the task objects you are gathering in variable $tasks that will contain the incremented number as property?

Something like this:

$id = 0
$tasks = Get-ScheduledTask | Get-ScheduledTaskInfo | 
         ForEach-Object {
             $_ | Select-Object TaskName, @{Name = 'TaskId'; Expression = {($script:id++)}},
                                LastRunTime,LastTaskResult
         }

foreach($task in $tasks) {
    if ($task.LastTaskResult -eq 0){
        Write-Host "0 MWT$($task.TaskId) - Scheduled task: $($task.TaskName) was succesfull"
    }
    else{
        Write-Host "2 MWT$($task.TaskId) - Scheduled task: $($task.TaskName) has failed."
    }
}
Theo
  • 57,719
  • 8
  • 24
  • 41
  • same problem, everytime i run the script each object have different id everytime script is run – Johny Wave Jun 02 '21 at 16:56
  • @JohnyWave yes, of course.. every time you call `Get-ScheduledTask` you'll get a different list of objects in a different order. Some tasks are new, some have ceased to be., It's not like you can permanently store an extra property in these objects, this only 'lives' for as long as you keep the array `$tasks`. – Theo Jun 02 '21 at 20:01