powershell increment value and give same value to same object everytime

358 Views Asked by At

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?

1

There are 1 best solutions below

2
On

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."
    }
}