0

Taking inspiration on Get informations on Windows Scheduled Task duration (execution time) we aim to filter on a set of tasks, instead of fetching all from task scheduler. something of this sort:

$logName = 'Microsoft-Windows-TaskScheduler/Operational'
$xPathFilter = @'
*[
    System[(EventID=200 or EventID=201)] and 
    EventData[
        Data[@Name="TaskName"] = "001_task_A_nightly"
    ]
]
'@

Get-WinEvent -LogName $logName -FilterXPath $xPathFilter | 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
         'Duration'  = ($end - $start).TotalSeconds

Is there a way to adapt this one above?

dmartins
  • 45
  • 8

1 Answers1

3

Use the -FilterXPath parameter set instead, it'll allow you to granularly filter on the contents of the underlying event XML:

$logName = 'Microsoft-Windows-TaskScheduler/Operational'
$xPathFilter = @'
*[
    System[(EventID=200 or EventID=201)] and 
    EventData[
        Data[@Name="TaskName"] = "\MyTask" or 
        Data[@Name="TaskName"] = "\MyOtherTask" or 
        Data[@Name="TaskName"] = "\TaskFolder\SomeThirdTask"
    ]
]
'@

Get-WinEvent -LogName $logName -FilterXPath $xPathFilter |Group-Object ...
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • couldn't make this work, does it work with `-like` "_persotasks" and how can I get the output as column values, like a SELECT statement? – dmartins Nov 03 '21 at 10:28
  • @dmartins No, XPath for event log only supports exact comparison, and the `TaskName` entry has to be the qualified path name of the task, so if the task you're looking for is located in the root path and called "dmartinsTask01", the `EventData` clause should be `Data[@Name="TaskName"] = "\dmartinsTask01"` (note that it's case-_sensitive_). – Mathias R. Jessen Nov 03 '21 at 10:33
  • understood. however i can't make this return anything. edited the question – dmartins Nov 03 '21 at 10:56
  • 1
    @dmartins change `"001_task_A_nightly"` to `"\001_task_A_nightly"` – Mathias R. Jessen Nov 03 '21 at 11:01