Get-WinEvent using -FilterHashTable and ActivityId/CorrelationId?

Good morning,

I’m using PowerShell v2/Server 2008 R2, and I need to get the duration time of a scheduled task only with the name of the task provided by the user. The way i’m currently doing it, is filtering schtasks.exe, getting the Last Run Time of that said task, filter the event log by that Last Run Time, checking that event log entry to see if contains an ActivityID and it contains my Task Name, grab that ActivityID, then filter the Event Log again for all tasks that match the captured ActivityID, then getting the timespan between the first EventLog and the last EventLog entries.

This can take up to 40 seconds if the task is very old, and i’m trying to find out a faster method. I was hoping i’d be able to add an option in the FilterHashTable for the CorrelationID/ActivityID but I couldn’t find a way to do it.

If you can point in the right direction to finding a faster method, that would be great.


function Get-TaskRunTime{ param([Parameter(Mandatory=$true)] [string]$taskName) $scheduledTasks = schtasks.exe /query /fo csv /v | convertfrom-csv | ?{$_.TaskName -match $taskName -and $_.TaskName -ne "TaskName"} if($scheduledTasks.Count -gt 1){ $task = $scheduledTasks[0] } else { $task = $scheduledTasks } $event = $null $taskTimeDate = [datetime]::ParseExact($task.'Last Run Time', 'dd/MM/yyyy h:mm:ss tt',[System.Globalization.CultureInfo]::InvariantCulture) $filterXml = @{ LogName = 'Microsoft-Windows-TaskScheduler/Operational'; ProviderName = 'Microsoft-Windows-TaskScheduler' ; StartTime = $taskTimeDate; } $eventCandidates = Get-WinEvent -FilterHashtable $filterXml -Oldest | ?{$_.ActivityID -ne $null} foreach($eventCandidate in $eventCandidates){ $addCandidate = $false foreach($property in ${ if($property.Value -match $taskName){ $event = $eventCandidate break; } } if($event){ break; } } $events = $eventCandidates | Sort-Object TimeCreated -Descending | ?{$_.ActivityId -match $event.ActivityId} $timeTaken = $(New-TimeSpan -Start $events[-1].TimeCreated -End $events[0].TimeCreated).ToString() write-host $timeTaken "hh:mm:ss.sss" } 

submitted by /u/Matty_R
[link] [comments]

Leave a Reply