0

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

1 Answer 1

0

($EndTime - $StartTime) will return the difference as a [TimeSpan] object.

Sign up to request clarification or add additional context in comments.

2 Comments

Did you mean $EndTime?
yeah, corrected the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.