I'm not a developer, but for administrative purposes, I need to make a script that will return the execution time of a task from the Task Scheduler in Windows. My idea was to first filter the Event Viewer for the name of my task, then extract 2 events with ID 100 and 102 (start event + finished event), and calculate the time difference between them. I used Get-WinEvent -FilterHashtable $filter for this and reached the point where my script returns 2 events properly. However, I have no idea how to extract date from the variables $EndTime and $StartTime. $timedifference shows current time from my system, so it's clearly wrong.
Question is: how to extract date from variables $EndTime and $StartTime and then calculate difference between them.
My script:
#Variables
$TaskName = '\TestTask'
$StartTime = (Get-Date).AddDays(-1)
$EndTime = Get-Date
$filter = @{
LogName = 'Microsoft-Windows-TaskScheduler/Operational'
ID = 100, 102
StartTime = $StartTime
EndTime = $EndTime
Data = $TaskName
}
# Retrieve events
$events = Get-WinEvent -FilterHashtable $filter | Select-Object TimeCreated, @{n='Action';e={$_.TaskDisplayName}}
# Calculate time difference
$timeDifference = New-TimeSpan -Start $StartTime -End $EndTime
# Output event details
$events