windowspowershellscheduled-taskstaskscheduler

Get informations on Windows Scheduled Task duration (execution time)


We have a couple of servers with hundred of scheduled tasks on them... and it is becoming problematic to find a right maintenance window. Is there some tool which allows for a graphical representation (like in a Gantt graph) of the Windows Task scheduler events?

Barring this, I've been fiddling with Powershell to implement the tool myself, using get-scheduledtask and get-scheduledtaskinfo, but while they do provide the properties LastRunTime and NextRunTime , I cannot find info about the duration of a task. I mean, If I started a task at 9AM, and the thread returned at 9.10, I do see in the history gui it ran for 10 minutes.., but I cannot get the same info using Powershell. Any hint? Thanks!


Solution

  • The information you're looking for is not persisted as a property of a task. You need to extract it from the task history. Beginning and end of an action are logged with ID 200 and 201 respectively.

    Get-WinEvent -FilterHashtable @{
        'LogName' = 'Microsoft-Windows-TaskScheduler/Operational'
        'ID'      = 200, 201
    } | Group-Object ActivityID | ForEach-Object {
        $start = $_.Group |
                 Where-Object { $_.Id -eq 200 } |
                 Select-Object -Expand TimeCreated -First 1
        $end   = $_.Group |
                 Where-Object { $_.Id -eq 201 } |
                 Select-Object -Expand TimeCreated -First 1
    
        New-Object -Type PSObject -Property @{
            'TaskName'  = $_.Group[0].Properties[0].Value
            'StartTime' = $start
            'Duration'  = ($end - $start).TotalSeconds
        }
    }