boot-perf.ps1 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. <#
  2. .SYNOPSIS
  3. Measure Windows boot performance from the Diagnostics-Performance
  4. log. Surfaces which boots were slow and what specifically dragged
  5. each one down.
  6. .DESCRIPTION
  7. The Microsoft-Windows-Diagnostics-Performance/Operational log records
  8. detailed timing for every boot event (boot main path, post-boot,
  9. total) and flags individual components that exceeded the system's
  10. "fast boot" threshold:
  11. Event 100 — "Windows successfully booted in X ms"
  12. Contains: BootTime, BootMainPathTime, BootPostBootTime,
  13. IsDegradation, IncidentTime
  14. Event 101 — "App took longer than usual to start"
  15. Event 102 — "Driver took longer than usual to start"
  16. Event 103 — "Service took longer than usual to start"
  17. Reading this log requires Administrator. Without admin, the script
  18. falls back to a kernel-event-based inference using Event 12 (kernel
  19. start) and Event 6005 (event log service started) — coarser but
  20. still useful for trend detection.
  21. .PARAMETER LastN
  22. Number of recent boots to report. Default: 10.
  23. .PARAMETER Json
  24. Machine-readable JSON output.
  25. .EXAMPLE
  26. scripts/boot-perf.ps1
  27. Show the last 10 boots with their durations and degradation flags.
  28. .EXAMPLE
  29. scripts/boot-perf.ps1 -LastN 30 -Json | jq '.boots[] | select(.degraded)'
  30. Filter to only degraded boots from machine-readable output.
  31. .NOTES
  32. Exit codes:
  33. 0 success
  34. 5 precondition (no boot events found at all)
  35. #>
  36. [CmdletBinding()]
  37. param(
  38. [ValidateRange(1, 100)][int]$LastN = 10,
  39. [switch]$Json
  40. )
  41. $ErrorActionPreference = 'Stop'
  42. . "$PSScriptRoot\_lib\common.ps1"
  43. . (Join-Path $PSScriptRoot '..\..\_lib\term.ps1')
  44. Initialize-Term
  45. $elevated = Test-IsElevated
  46. $boots = New-Object System.Collections.Generic.List[hashtable]
  47. $slowComponents = New-Object System.Collections.Generic.List[hashtable]
  48. $source = 'diagnostics-perf'
  49. # ─────────────────────────────────────────────────────────────────────
  50. # Primary: Diagnostics-Performance log (requires admin)
  51. # ─────────────────────────────────────────────────────────────────────
  52. try {
  53. $perfEvents = Get-WinEvent -LogName 'Microsoft-Windows-Diagnostics-Performance/Operational' `
  54. -ErrorAction Stop |
  55. Where-Object { $_.Id -in @(100, 101, 102, 103) }
  56. foreach ($e in $perfEvents | Where-Object { $_.Id -eq 100 }) {
  57. # Properties layout (Event 100):
  58. # [1] BootTime
  59. # [4] BootMainPathTime
  60. # [5] BootPostBootTime
  61. # [6] BootIsDegradation
  62. try {
  63. $bootTotal = [int64]$e.Properties[1].Value
  64. $bootMain = [int64]$e.Properties[4].Value
  65. $bootPost = [int64]$e.Properties[5].Value
  66. $degraded = [bool]$e.Properties[6].Value
  67. } catch {
  68. $bootTotal = -1; $bootMain = -1; $bootPost = -1; $degraded = $false
  69. }
  70. $boots.Add(@{
  71. time = $e.TimeCreated.ToString('o')
  72. bootTotalSec = if ($bootTotal -gt 0) { [math]::Round($bootTotal / 1000, 1) } else { -1 }
  73. bootMainSec = if ($bootMain -gt 0) { [math]::Round($bootMain / 1000, 1) } else { -1 }
  74. bootPostSec = if ($bootPost -gt 0) { [math]::Round($bootPost / 1000, 1) } else { -1 }
  75. degraded = $degraded
  76. })
  77. }
  78. # Slow components — events 101/102/103
  79. foreach ($e in $perfEvents | Where-Object { $_.Id -in @(101, 102, 103) }) {
  80. $kind = switch ($e.Id) { 101 {'app'} 102 {'driver'} 103 {'service'} }
  81. # Property layout varies by event id; the friendly name + delay are
  82. # usually accessible by reading the rendered message string.
  83. $msg = ($e.Message -replace '\s+', ' ')
  84. $delaySec = $null
  85. if ($msg -match '(\d+) ms') {
  86. $delaySec = [math]::Round([int]$matches[1] / 1000, 1)
  87. }
  88. # Name extraction varies; try common patterns
  89. $name = '(unknown)'
  90. if ($msg -match '"([^"]+)"') { $name = $matches[1] }
  91. elseif ($msg -match 'Name\s*:\s*(\S+)') { $name = $matches[1] }
  92. $slowComponents.Add(@{
  93. time = $e.TimeCreated.ToString('o')
  94. kind = $kind
  95. name = $name
  96. delaySec = $delaySec
  97. message = (Format-EventMessage -Message $msg -MaxLength 200)
  98. })
  99. }
  100. }
  101. catch {
  102. $source = 'kernel-events'
  103. if (-not $elevated) {
  104. Write-Log -Level WARN -Message "Cannot read Diagnostics-Performance log (admin required). Falling back to coarse kernel-event timing."
  105. } else {
  106. Write-Log -Level WARN -Message "Diagnostics-Performance log unavailable: $_"
  107. }
  108. # ─────────────────────────────────────────────────────────────────
  109. # Fallback: kernel event 12 (start) + 6005 (event log started)
  110. # Gap = approximate "kernel → services running" time. Not full boot
  111. # to usable desktop but a useful trend metric.
  112. # ─────────────────────────────────────────────────────────────────
  113. try {
  114. $kernelStarts = Get-WinEvent -FilterHashtable @{
  115. LogName='System'; Id=12; ProviderName='Microsoft-Windows-Kernel-General'
  116. } -MaxEvents 30 -ErrorAction SilentlyContinue
  117. $logStarts = Get-WinEvent -FilterHashtable @{
  118. LogName='System'; Id=6005
  119. } -MaxEvents 30 -ErrorAction SilentlyContinue
  120. foreach ($k in $kernelStarts) {
  121. # Find the 6005 closest after this 12 (within 5 min)
  122. $matchingLog = $logStarts | Where-Object {
  123. $_.TimeCreated -gt $k.TimeCreated -and ($_.TimeCreated - $k.TimeCreated).TotalSeconds -lt 300
  124. } | Sort-Object TimeCreated | Select-Object -First 1
  125. if ($matchingLog) {
  126. $delta = ($matchingLog.TimeCreated - $k.TimeCreated).TotalSeconds
  127. $boots.Add(@{
  128. time = $k.TimeCreated.ToString('o')
  129. bootTotalSec = -1 # not available without diagnostics-perf
  130. bootMainSec = [math]::Round($delta, 1)
  131. bootPostSec = -1
  132. degraded = $false
  133. note = 'inferred from kernel start -> event log start; not full boot duration'
  134. })
  135. }
  136. }
  137. } catch {}
  138. }
  139. # Trim to LastN
  140. $boots = $boots | Sort-Object { [DateTime]$_.time } -Descending | Select-Object -First $LastN
  141. # ─────────────────────────────────────────────────────────────────────
  142. # Output
  143. # ─────────────────────────────────────────────────────────────────────
  144. if ($Json) {
  145. @{
  146. source = $source
  147. elevated = $elevated
  148. boots = $boots
  149. slowComponents = $slowComponents | Sort-Object { [DateTime]$_.time } -Descending | Select-Object -First 30
  150. } | ConvertTo-Json -Depth 5 | ForEach-Object { [Console]::Out.WriteLine($_) }
  151. exit $script:EXIT_OK
  152. }
  153. if (-not $boots) {
  154. Write-Log -Level FAIL -Message "No boot events found"
  155. exit $script:EXIT_PRECONDITION
  156. }
  157. # Median + average for the summary line (whichever data we have)
  158. $mainSecs = $boots | ForEach-Object { $_.bootMainSec } | Where-Object { $_ -gt 0 }
  159. $median = if ($mainSecs.Count -ge 1) {
  160. $sorted = $mainSecs | Sort-Object
  161. $sorted[[math]::Floor($sorted.Count / 2)]
  162. } else { 0 }
  163. $avg = if ($mainSecs.Count -ge 1) {
  164. [math]::Round(($mainSecs | Measure-Object -Average).Average, 1)
  165. } else { 0 }
  166. $sourceLabel = if ($source -eq 'diagnostics-perf') { 'full data' } else { 'fallback mode' }
  167. Write-TermLine (New-TermPanelOpen -Brand 'windows-ops' -Name 'windows-ops' -Subtitle 'boot-perf' -Indicator $sourceLabel)
  168. Write-TermLine (New-TermPanelVert)
  169. Write-TermLine (New-TermSummary -Text "$($boots.Count) boots · median ${median}s · avg ${avg}s")
  170. if (-not $elevated -and $source -ne 'diagnostics-perf') {
  171. Write-TermLine (New-TermHint -Text 'run as Administrator for full Diagnostics-Performance log (boot phases + slow-component flags)')
  172. }
  173. Write-TermLine (New-TermPanelVert)
  174. Write-TermLine (New-TermSection -State 'INFO' -Label 'boot timeline' -Count $boots.Count)
  175. # Find slowest in window for highlighting
  176. $slowestSec = ($mainSecs | Measure-Object -Maximum).Maximum
  177. $idxLast = $boots.Count - 1
  178. for ($i = 0; $i -lt $boots.Count; $i++) {
  179. $b = $boots[$i]
  180. $t = ([DateTime]$b.time).ToString('yyyy-MM-dd HH:mm')
  181. $secVal = if ($b.bootMainSec -gt 0) { $b.bootMainSec } else { 0 }
  182. # Capacity pip bar: relative to 20-second ceiling (anything ≥80% = red)
  183. $bar = New-TermPipBar -Type capacity -Filled ([int]($secVal * 5)) -Total 100
  184. $meta = "${secVal}s"
  185. if ($b.degraded) { $meta += ' [DEGRADED]' }
  186. Write-TermLine (New-TermLeaf -Name $t -Rail $bar -Meta $meta -IsLast:($i -eq $idxLast) -NameColWidth 20)
  187. if ($secVal -eq $slowestSec -and $boots.Count -gt 3 -and $secVal -gt 0) {
  188. Write-TermLine (New-TermAlert -Severity warning -Text "slowest in window · ${secVal}s vs median ${median}s")
  189. }
  190. }
  191. Write-TermLine (New-TermPanelVert)
  192. # Slow components section
  193. $recentSlow = $slowComponents | Sort-Object { [DateTime]$_.time } -Descending | Select-Object -First 10
  194. if ($recentSlow) {
  195. Write-TermLine (New-TermSection -State 'WARN' -Label 'slow components' -Count $recentSlow.Count)
  196. $idxLast = $recentSlow.Count - 1
  197. for ($i = 0; $i -lt $recentSlow.Count; $i++) {
  198. $s = $recentSlow[$i]
  199. $delay = if ($s.delaySec) { "$($s.delaySec)s" } else { '?' }
  200. $when = ([DateTime]$s.time).ToString('MM-dd HH:mm')
  201. Write-TermLine (New-TermLeaf -Name "[$($s.kind)] $($s.name)" -Meta $delay -Age $when -IsLast:($i -eq $idxLast) -NameColWidth 36)
  202. }
  203. Write-TermLine (New-TermAlert -Severity warning -Text 'repeat offenders → safe-disable-startup.ps1 (apps) or Set-Service -StartupType Manual (services)')
  204. Write-TermLine (New-TermPanelVert)
  205. }
  206. # Footer
  207. $health = if ($elevated -and $source -eq 'diagnostics-perf') {
  208. New-TermHealth -State 'healthy' -Text 'full data'
  209. } else {
  210. New-TermHealth -State 'pending' -Text 'fallback'
  211. }
  212. $hk = (New-TermHotkey -Key '?' -Verb 'help')
  213. Write-TermLine (New-TermPanelClose -Hotkeys $hk -Healths $health)
  214. exit $script:EXIT_OK