Skip to content

Commit bb226d4

Browse files
truculeclaude
andauthored
Fix sleep and wake pairing and DST-safe sleep duration
Pick the event 42 closest to SleepTime so a later sleep's event in the window isn't matched, and compute Asleep from the DateTimeOffset values so a sleep across a daylight saving change has the right length. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AXY6pfEzpyB9Cjasa4B4S9
1 parent cbbf6c5 commit bb226d4

1 file changed

Lines changed: 5 additions & 4 deletions

File tree

  • content/articles/2026/11/find-what-wakes-a-windows-pc-with-get-winevent

‎content/articles/2026/11/find-what-wakes-a-windows-pc-with-get-winevent/index.md‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -130,10 +130,11 @@ function Get-SleepWakeHistory {
130130
$sleptAt = [datetimeoffset]::Parse($w.SleepTime).LocalDateTime
131131
$wokeAt = [datetimeoffset]::Parse($w.WakeTime).LocalDateTime
132132
133-
# Event 42 is written within seconds of the SleepTime that event 1 records.
133+
# Event 42 is written within seconds of the SleepTime that event 1 records, so take the closest one.
134134
$entry = $sleeps |
135135
Where-Object { $_.TimeCreated -ge $sleptAt.AddMinutes(-2) -and $_.TimeCreated -le $sleptAt.AddMinutes(1) } |
136-
Select-Object -Last 1
136+
Sort-Object { [math]::Abs(($_.TimeCreated - $sleptAt).TotalSeconds) } |
137+
Select-Object -First 1
137138
138139
$reason = 'No event 42 found'
139140
if ($entry) {
@@ -154,7 +155,7 @@ function Get-SleepWakeHistory {
154155
ComputerName = $ComputerName
155156
Slept = $sleptAt
156157
Woke = $wokeAt
157-
Asleep = New-TimeSpan -Start $sleptAt -End $wokeAt
158+
Asleep = [datetimeoffset]::Parse($w.WakeTime) - [datetimeoffset]::Parse($w.SleepTime)
158159
SleepReason = $reason
159160
WakeSource = $source
160161
WakeTimer = $w.WakeTimerOwner
@@ -191,7 +192,7 @@ WakeSource : Unknown
191192
WakeTimer :
192193
```
193194

194-
In both rows event 42 was written 1 to 5 seconds after the `SleepTime` in event 1. Across 20 sleeps on that laptop the gap was never more than 13 seconds, which is why the function looks 2 minutes back and 1 minute forward.
195+
In both rows event 42 was written 1 to 5 seconds after the `SleepTime` in event 1. Across 20 sleeps on that laptop the gap was never more than 13 seconds, which is why the function looks 2 minutes back and 1 minute forward. When two event 42s fall in that window, as they can after a very short sleep, it takes the one closest to the `SleepTime`.
195196

196197
A wake you caused shows the power button, the lid, or the device you touched as the source. The rows to look at are the ones that happened when nobody was at the PC. For those, the wake source is usually a timer, which points at a scheduled task, or a device such as a network adapter or a mouse.
197198

0 commit comments

Comments
 (0)