diff --git a/WindowsMaintenanceReport.ps1 b/WindowsMaintenanceReport.ps1 index 45e2f90..b4f7b38 100644 --- a/WindowsMaintenanceReport.ps1 +++ b/WindowsMaintenanceReport.ps1 @@ -1,638 +1,903 @@ -id: "BEF-2026-09-14-CLEVO-002" - -organization: "Beffroi" - -title: "System Stability Investigation — Storage / Firmware Follow-up" -subtitle: "PC Specialist / Clevo — exhaustive diagnostic record and current assessment" - -report_type: technical -theme: default - -status: "open" -severity: "high" - -metadata: - Date: "2026-09-14" - Device: "DESKTOP-SAU019H" - Model: "PC Specialist / Clevo NH5x_NH7x_HHx_HJx_HKx" - Motherboard: "CLEVO NHxxHJHK" - BIOS: "Insyde 1.07.07TPCS1 — 2021-09-16" - CPU: "Intel Core i7-11800H" - Memory: "16 GB" - GPU: "Intel UHD Graphics + NVIDIA GeForce GTX 1650" - OS: "Windows 11 Pro — image version 10.0.26200.9168" - SATAStorage: "128GB PCS 2.5-inch SSD — serial U9DI16295T" - NVMeStorage: "1TB PCS PCIe M.2 SSD — Silicon Motion NVMe controller PCI VEN_126F DEV_2263" - Author: "Maximilien Rigaut" - Purpose: "Continuation and consolidation of the 2026-09-04 Clevo stability investigation" - -summary: > - The investigation of DESKTOP-SAU019H was resumed on 2026-09-14 after earlier - hard freezes, shutdown anomalies, an NVRAM-reset firmware warning, TPM / - Measured Boot errors and repeated NVMe controller errors. Fast Startup was - disabled by disabling hibernation. DISM successfully repaired the Windows - component store and SFC found and repaired protected system-file corruption; - a subsequent SFC scan after restart reported no remaining integrity - violations. Storage enumeration before restart exposed only the 128 GB SATA - SSD through Get-Disk and Get-PhysicalDisk, while the 1 TB NVMe remained known - to Plug and Play. After restart, Windows positively enumerated the 1 TB PCS - PCIe M.2 SSD and its Standard NVM Express Controller as present and working - properly, with the controller linked at PCIe Gen3 x4, but Get-Disk still - exposed only the 128 GB SATA SSD. A new stornvme Event 11 occurred at - 16:23:21 on 2026-09-14, reporting a controller error on \Device\RaidPort2. - Historical Event 129 resets and Event 11 controller errors against the same - RaidPort2 are present on 2026-09-04 and repeatedly as far back as March 2026. - The BIOS menus inspected during this session did not list the 1 TB NVMe/SATA - device. The strongest current lead is therefore an intermittent or partial - failure somewhere in the 1 TB NVMe storage path: the SSD itself, its M.2 - connection, PCIe link / slot, controller behaviour, firmware interaction or - power delivery. A failing SSD is not yet conclusively proven. The NVRAM / - CMOS issue remains a separate open diagnostic track. - -timeline: - - time: "2026-09-04 ~15:21" - event: "NVMe controller error" - notes: > - stornvme Event 11 reported a controller error on \Device\RaidPort2. - - - time: "2026-09-04 ~16:30" - event: "Firmware / NVRAM warning" - notes: > - Firmware displayed a first-boot or NVRAM-reset-condition warning. - - - time: "2026-09-04 ~16:32" - event: "TPM / Measured Boot failure" - notes: > - TPM-WMI Event 1040 reported a critical pre-attestation health-check - failure and referenced a MeasuredBoot diagnostic JSON file. - - - time: "2026-09-04 ~16:44" - event: "Second confirmed NVMe controller error" - notes: > - stornvme Event 11 again reported a controller error on - \Device\RaidPort2. - - - time: "2026-09-04 ~16:53" - event: "Normal shutdown failure" - notes: > - Windows shutdown hung and a forced power-off was required. - - - time: "2026-09-04 later" - event: "Restart test" - notes: > - A normal Windows restart completed successfully. - - - time: "2026-09-04 later" - event: "Full-shutdown test bypassing Fast Startup" - notes: > - A full shutdown completed normally when Fast Startup was bypassed. - - - time: "2026-09-04 <17:23" - event: "Hard freeze" - notes: > - A system freeze occurred before further configuration changes. - - - time: "2026-09-04 ~17:25" - event: "Second hard freeze" - notes: > - A second freeze / hang was observed. - - - time: "2026-09-14 before storage retest" - event: "Fast Startup disabled" - notes: > - powercfg /h off completed without error. Hibernation was disabled, - which also disables Windows Fast Startup. - - - time: "2026-09-14 before storage retest" - event: "DISM CheckHealth syntax attempt" - notes: > - DISM /CheckHealth returned Error 87 because /Online /Cleanup-Image - were omitted. This was a command syntax issue and not a diagnostic - failure. - - - time: "2026-09-14 before storage retest" - event: "DISM component-store repair" - notes: > - DISM /Online /Cleanup-Image /RestoreHealth completed at 100 percent. - DISM reported that the restore operation and overall operation - completed successfully. - - - time: "2026-09-14 before storage retest" - event: "SFC system-file repair" - notes: > - sfc /scannow found corrupt files and successfully repaired them. - - - time: "2026-09-14 before restart" - event: "Initial disk inventory" - notes: > - Get-Disk exposed only Disk 0, the 128GB PCS 2.5-inch SATA SSD, - Online and Healthy. The 1 TB NVMe was absent from Get-Disk. - - - time: "2026-09-14 before restart" - event: "Initial physical-disk inventory" - notes: > - Get-PhysicalDisk exposed only the 128GB PCS 2.5-inch SATA SSD, - Healthy / OK. The 1 TB NVMe was absent from this storage-provider view. - - - time: "2026-09-14 before restart" - event: "PnP controller inventory" - notes: > - A Standard NVM Express Controller with hardware ID PCI\VEN_126F&DEV_2263 - existed in Plug and Play history but was initially shown with status - Unknown in the non-PresentOnly query. - - - time: "2026-09-14 before restart" - event: "PnP disk inventory" - notes: > - A 1TB PCS PCIe M.2 SSD device entry existed in Plug and Play history - but was initially shown with status Unknown in the non-PresentOnly - query. Numerous historical USB storage entries were also present, - demonstrating that this query included devices not currently attached. - - - time: "2026-09-14 before restart" - event: "SATA reliability telemetry" - notes: > - Get-StorageReliabilityCounter returned data for DeviceId 0, the visible - 128 GB SATA SSD: 2033 power-on hours, 40 C temperature, wear 0, - ReadErrorsTotal 0, ReadErrorsUncorrected 0, maximum read latency - 4253 ms and maximum write latency 6122 ms. This telemetry did not - describe the 1 TB NVMe. - - - time: "2026-09-14 restart / BIOS inspection" - event: "BIOS storage inspection" - notes: > - The BIOS menus inspected by the operator did not show a 1 TB NVMe or - SATA storage device. This observation is retained as evidence, but the - exact Clevo/Insyde BIOS menu capabilities have not been established; - absence from a BIOS menu does not by itself prove failure to enumerate - the PCIe function. - - - time: "2026-09-14 16:15:38" - event: "NVMe controller arrival after reboot" - notes: > - Windows recorded the Standard NVM Express Controller LastArrivalDate - as 2026-09-14 16:15:38. - - - time: "2026-09-14 ~16:15 onward" - event: "PresentOnly controller enumeration" - notes: > - Get-PnpDevice -PresentOnly positively enumerated the Standard NVM - Express Controller as present with Status OK. - - - time: "2026-09-14 ~16:15 onward" - event: "PresentOnly 1 TB NVMe disk enumeration" - notes: > - Get-PnpDevice -PresentOnly -Class DiskDrive positively enumerated - 1TB PCS PCIe M.2 SSD with Status OK alongside the 128 GB SATA SSD. - - - time: "2026-09-14 ~16:15 onward" - event: "Get-Disk still omitted NVMe" - notes: > - Despite positive current PnP enumeration of the NVMe controller and - disk device, Get-Disk still exposed only the 128 GB SATA SSD. - - - time: "2026-09-14 ~16:15 onward" - event: "NVMe controller state inspected" - notes: > - The controller reported CM_PROB_NONE, ConfigManagerErrorCode - CM_PROB_NONE, Status OK, Present True, HasProblem False and service - stornvme. - - - time: "2026-09-14 ~16:15 onward" - event: "NVMe PCIe link inspected" - notes: > - Device properties reported PCI bus 2, device 0, function 0, - CurrentLinkSpeed 3, CurrentLinkWidth 4, MaxLinkSpeed 3 and - MaxLinkWidth 4. The controller was therefore actively enumerated on a - PCIe Gen3 x4 link at the time of inspection. - - - time: "2026-09-14 16:23:21" - event: "New NVMe controller error" - notes: > - stornvme Event 11 reported: "The driver detected a controller error on - \Device\RaidPort2." This event occurred during the current diagnostic - session after the NVMe controller had arrived and been enumerated. - - - time: "2026-09-14 after 16:23" - event: "Historical stornvme event review" - notes: > - Event-log review confirmed repeated Event 129 device resets and - Event 11 controller errors on \Device\RaidPort2 on 2026-09-04 and - repeatedly in June and March 2026. The pattern therefore predates the - September incident. - - - time: "2026-09-14 after event review" - event: "Post-repair SFC verification" - notes: > - A second sfc /scannow completed with "Windows Resource Protection did - not find any integrity violations." - -findings: - - title: "Fast Startup disabled for diagnosis" - severity: "info" - status: "completed" - evidence: > - powercfg /h off completed successfully. - assessment: > - Disabling hibernation disables Windows Fast Startup and removes the - previously observed Fast Startup path from subsequent shutdown and boot - tests. This is an appropriate diagnostic control and should remain in - place until the investigation is complete. - - - title: "Windows component-store corruption" - severity: "medium" - status: "repaired" - evidence: > - DISM /Online /Cleanup-Image /RestoreHealth completed successfully. - assessment: > - A Windows integrity problem existed and was repaired. The evidence does - not establish whether corruption contributed to the hard freezes, - resulted from forced power-offs, or was unrelated. - - - title: "Protected Windows system-file corruption" - severity: "medium" - status: "repaired" - evidence: > - The first sfc /scannow found corrupt files and repaired them. A later - sfc /scannow after restart reported no integrity violations. - assessment: > - Windows protected-file integrity is currently clean. Recurrent immediate - corruption was not observed after repair and reboot. - - - title: "1 TB NVMe absent from Get-Disk / Get-PhysicalDisk" - severity: "high" - status: "confirmed" - evidence: > - Before restart, both Get-Disk and Get-PhysicalDisk exposed only the - 128 GB PCS SATA SSD. After restart, Get-Disk still exposed only the - SATA SSD even though PresentOnly PnP enumeration showed the NVMe - controller and 1 TB NVMe disk as currently present. - assessment: > - Windows can enumerate the PCIe NVMe function and child disk device but - does not currently expose the 1 TB NVMe as a normal usable disk through - the storage-management layer. This strongly supports a problem in the - NVMe storage path rather than a simple stale Device Manager entry. - - - title: "1 TB NVMe positively present on PCIe after reboot" - severity: "high" - status: "confirmed" - evidence: > - Get-PnpDevice -PresentOnly reported the Standard NVM Express Controller - and 1TB PCS PCIe M.2 SSD as present with Status OK. The controller - reported Present True, HasProblem False, CM_PROB_NONE and a PCIe Gen3 - x4 link. - assessment: > - The controller was physically enumerated at the PCIe level during the - session. Therefore the device was not simply absent from the PCIe bus at - the moment these properties were queried. This does not demonstrate - reliable access to the NVMe media. - - - title: "Current-session stornvme controller error" - severity: "high" - status: "confirmed" - evidence: > - stornvme Event 11 occurred at 2026-09-14 16:23:21 and reported a - controller error on \Device\RaidPort2. - assessment: > - This is direct evidence of an active storage-controller/path failure - during the current session. It materially raises the priority of the - 1 TB NVMe path as a potential explanation for the historical freezes. - - - title: "Long-running RaidPort2 reset / error pattern" - severity: "high" - status: "confirmed" - evidence: > - Historical logs contain repeated stornvme Event 129 resets and Event 11 - controller errors on \Device\RaidPort2 on 2026-09-04 and repeatedly in - June and March 2026. - assessment: > - The storage-path problem is recurrent and predates the September 2026 - hard-freeze investigation. This makes a one-off Windows corruption event - an insufficient explanation for the controller-error history. - - - title: "NVMe physical failure not yet proven" - severity: "high" - status: "open" - evidence: > - The NVMe controller and child disk can currently enumerate on PCIe and - report PnP Status OK, while stornvme simultaneously records controller - errors and the disk remains absent from Get-Disk. - assessment: > - The evidence is compatible with a failing NVMe SSD, but does not yet - distinguish the SSD itself from the M.2 connection, motherboard slot / - PCIe path, controller firmware, system firmware interaction or power - delivery. The drive should not yet be condemned solely from Event 11. - - - title: "BIOS does not list 1 TB storage device in inspected menus" - severity: "medium" - status: "observed" - evidence: > - During the 2026-09-14 BIOS inspection, no 1 TB NVMe/SATA device was - visible to the operator. - assessment: > - Retain this as an important observation. However, the available evidence - does not establish whether this specific Insyde BIOS exposes NVMe device - inventory in its UI. Windows later demonstrated active PCIe enumeration, - so absence from the visible BIOS menus must not be treated as conclusive - proof that firmware failed to enumerate the controller. - - - title: "NVRAM / CMOS retention issue" - severity: "high" - status: "open" - evidence: > - The original firmware warning reported a first-boot or NVRAM-reset - condition. - assessment: > - The warning remains unexplained. A failed RTC/CMOS battery is possible - but not proven. A controlled unpowered retention test of BIOS time and - settings remains required. This issue should remain diagnostically - separate from the NVMe fault unless further evidence connects them. - - - title: "TPM / Measured Boot pre-attestation failure" - severity: "medium" - status: "open" - evidence: > - TPM-WMI Event 1040 previously reported a critical pre-attestation - health-check failure and referenced a MeasuredBoot JSON diagnostic file. - assessment: > - The temporal association with the NVRAM warning makes a firmware-state - relationship plausible, but no causal relationship has been proven. - The TPM should not be cleared merely as a diagnostic experiment. - - - title: "128 GB SATA SSD telemetry" - severity: "info" - status: "currently-normal" - evidence: > - The visible SATA SSD reported Healthy / OK, 40 C, wear 0, - ReadErrorsTotal 0 and ReadErrorsUncorrected 0 in the supplied reliability - counter output. - assessment: > - No direct read-error evidence was observed for the 128 GB SATA SSD in - this checkpoint. The unusually high recorded maximum latency values are - retained for completeness but are not by themselves sufficient to - diagnose failure. - -sections: - - title: "Commands and results — boot / shutdown control" - content: - - type: bullets - items: - - > - powercfg /h off — completed without error; hibernation and Fast - Startup disabled. - - > - Previous full-shutdown test bypassing Fast Startup — completed - normally. - - > - Previous normal restart test — completed normally. - - - title: "Commands and results — Windows integrity" - content: - - type: bullets - items: - - > - DISM /CheckHealth — returned Error 87 because the required - /Online /Cleanup-Image arguments were omitted. This result has no - diagnostic significance for Windows health. - - > - DISM /Online /Cleanup-Image /RestoreHealth — reached 100 percent - and completed successfully. - - > - First sfc /scannow — found corrupt files and successfully - repaired them. - - > - Second sfc /scannow after restart — no integrity violations found. - - - title: "Commands and results — initial storage inventory" - content: - - type: bullets - items: - - > - Get-Disk — only Disk 0, 128GB PCS 2.5-inch SSD, SATA, Online, - Healthy, 128035676160 bytes. - - > - Get-PhysicalDisk — only 128GB PCS 2.5-inch SSD, SSD/SATA, - Healthy / OK, 128035676160 bytes. - - > - Get-PnpDevice -Class SCSIAdapter — historical list included a - Standard NVM Express Controller with PCI VEN_126F DEV_2263, - initially shown as Unknown without -PresentOnly. - - > - Get-PnpDevice -Class DiskDrive — historical list included - 1TB PCS PCIe M.2 SSD, initially shown as Unknown without - -PresentOnly, along with many disconnected historical USB devices. - - > - Get-StorageReliabilityCounter — returned telemetry only for the - visible DeviceId 0 / 128 GB SATA SSD: 2033 power-on hours, 40 C, - wear 0, no reported read errors. - - - title: "Commands and results — post-reboot NVMe enumeration" - content: - - type: bullets - items: - - > - Get-PnpDevice -PresentOnly -Class SCSIAdapter — Standard NVM - Express Controller present, Status OK. - - > - Get-PnpDevice -PresentOnly -Class DiskDrive — 1TB PCS PCIe M.2 SSD - present, Status OK; 128GB PCS 2.5-inch SSD also present. - - > - Get-Disk — still exposed only the 128 GB SATA SSD. - - > - PresentOnly PCI VEN_126F DEV_2263 query — controller Status OK, - class SCSIAdapter. - - > - Controller detailed properties — CM_PROB_NONE, - ConfigManagerErrorCode CM_PROB_NONE, Present True, - HasProblem False, Service stornvme. - - > - Controller PCI properties — bus 2, device 0, function 0; - current and maximum link speed 3; current and maximum link width 4; - AER capability present. - - > - Controller LastArrivalDate — 2026-09-14 16:15:38. - - > - Controller bus relation and child relationship both reference - SCSI\Disk&Ven_NVMe&Prod_1TB_PCS_PCIe_M.2. - - - title: "Commands and results — storage event history" - content: - - type: bullets - items: - - > - 2026-09-14 16:23:21 — stornvme Event 11: - controller error on \Device\RaidPort2. - - > - 2026-09-04 17:22:40 — stornvme Event 11: - controller error on \Device\RaidPort2. - - > - 2026-09-04 17:20:46 — stornvme Event 129: - reset to \Device\RaidPort2 issued. - - > - 2026-09-04 17:12:39 — stornvme Event 129: - reset to \Device\RaidPort2 issued. - - > - 2026-09-04 16:57:14 — stornvme Event 11: - controller error on \Device\RaidPort2. - - > - 2026-09-04 16:55:20 — stornvme Event 129: - reset to \Device\RaidPort2 issued. - - > - 2026-09-04 16:44:57 — stornvme Event 11: - controller error on \Device\RaidPort2. - - > - 2026-09-04 16:43:03 — stornvme Event 129: - reset to \Device\RaidPort2 issued. - - > - 2026-09-04 15:21:28 — stornvme Event 11: - controller error on \Device\RaidPort2. - - > - 2026-09-04 15:19:32 — stornvme Event 129: - reset to \Device\RaidPort2 issued. - - > - Additional Event 11 / Event 129 occurrences were confirmed on - 2026-06-09, 2026-06-08, 2026-03-26, 2026-03-21, 2026-03-20, - 2026-03-19 and 2026-03-18. - - - title: "BIOS / firmware observations" - content: - - type: bullets - items: - - > - Earlier investigation observed: "A first boot or NVRAM reset - condition has been detected." - - > - BIOS used during this investigation: Insyde 1.07.07TPCS1. - - > - Operator inspection on 2026-09-14 found no visible 1 TB NVMe/SATA - device in the BIOS menus examined. - - > - No BIOS update or firmware flash has been performed during this - diagnostic sequence. - - > - No TPM clear has been performed. - - - title: "Interpretation at this checkpoint" - content: - - type: callout - title: "Current state" - kind: "warning" - text: > - Windows software integrity has been repaired and verified clean, but - the storage problem remains active. The 1 TB NVMe controller and - child disk can enumerate on PCIe while the disk remains absent from - Get-Disk, and a new Event 11 controller error was generated during - the current session. This substantially strengthens the NVMe / - M.2 / PCIe storage-path hypothesis for the hard-freeze investigation. - It still does not identify which physical component in that path is - defective. - - - type: bullets - items: - - "Fast Startup is disabled and should remain disabled during diagnosis." - - "Windows component-store corruption has been repaired." - - "Windows protected system files are currently clean." - - "The 128 GB SATA SSD is the only disk exposed by Get-Disk." - - "The 1 TB NVMe controller is currently enumerated on PCIe Gen3 x4." - - "The 1 TB NVMe child disk is currently visible to PresentOnly PnP." - - "The 1 TB NVMe is nevertheless absent from Get-Disk." - - "A new stornvme Event 11 occurred during this diagnostic session." - - "RaidPort2 Event 11 / 129 faults recur over several months." - - "The 1 TB SSD itself is a primary suspect but is not yet conclusively proven defective." - - "M.2 seating, slot / motherboard path and power delivery remain plausible alternatives." - - "The NVRAM / CMOS issue remains open and should not yet be merged with the NVMe diagnosis." - - "TPM / Measured Boot evidence remains preserved and unresolved." - - "A BIOS flash is not currently justified as a first remediation step." - -actions_title: "Recommended next diagnostic steps" - -actions: - - title: "Back up important data" - status: "priority" - text: > - Ensure all important data is backed up before further manipulation or - testing. Recurrent NVMe controller resets/errors justify treating the - storage path as potentially unreliable. - - - title: "Perform controlled full shutdown" - status: "pending" - text: > - With Fast Startup already disabled, perform a full shutdown before any - physical inspection. - commands: - - "shutdown /s /t 0" - - - title: "Physically inspect and reseat the 1 TB M.2 NVMe" - status: "pending" - text: > - Disconnect AC power and, where service procedure permits, disconnect - the internal battery before handling the M.2 drive. Photograph the SSD - label and exact part number. Inspect the retaining screw, seating, - contacts and socket; remove and firmly reseat the SSD. Do not change - unrelated firmware settings during the same test. - - - title: "Retest storage enumeration after reseat" - status: "pending" - text: > - After reseating, boot the machine and determine whether the 1 TB NVMe - becomes a normal disk and whether new stornvme errors appear. - commands: - - "Get-Disk" - - "Get-PhysicalDisk" - - "Get-PnpDevice -PresentOnly -Class SCSIAdapter" - - "Get-PnpDevice -PresentOnly -Class DiskDrive" - - - title: "Review post-reseat stornvme events" - status: "pending" - text: > - Check the System log for fresh Event 11 or Event 129 entries immediately - after the test boot. - commands: - - "Get-WinEvent -FilterHashtable @{ LogName='System'; ProviderName='stornvme'; StartTime=(Get-Date).AddMinutes(-30) } | Format-List TimeCreated, Id, LevelDisplayName, Message" - - - title: "Isolate SSD versus motherboard path if errors persist" - status: "pending" - text: > - If the NVMe remains absent from Get-Disk or Event 11 / 129 recurs after - reseating, test the SSD in another known-good compatible M.2 slot, - external NVMe enclosure or another system where practical. Conversely, - test a known-good compatible NVMe in the Clevo slot if available. The - purpose is to distinguish drive failure from slot / motherboard / power - failure before replacing parts. - - - title: "Perform NVRAM / CMOS retention test" - status: "pending" - text: > - Record BIOS date/time and relevant settings, fully power down, disconnect - AC for an extended interval, then boot directly into BIOS and verify - retention. If settings or time are lost, investigate the RTC/CMOS battery, - its connection and the motherboard RTC power path. - - - title: "Preserve TPM / Measured Boot evidence" - status: "pending" - text: > - Keep the referenced MeasuredBoot JSON before any TPM, Secure Boot or - firmware reset operation. Do not clear the TPM solely as a diagnostic - experiment. - commands: - - 'C:\WINDOWS\Logs\MeasuredBoot\0000000053-0000000000.json' - - - title: "Defer BIOS flashing" - status: "hold" - text: > - Do not flash BIOS/EC firmware while the machine has an unresolved - intermittent storage fault unless a later, model-specific remediation - path explicitly requires it and power/storage stability has first been - established. - -closing: > - At this checkpoint the Windows repair is complete and verified, while the - storage-path fault remains active and repeatable. The strongest evidence is - the coexistence of a currently enumerated PCIe Gen3 x4 NVMe controller, - failure of the 1 TB NVMe to appear in Get-Disk, and a fresh stornvme Event 11 - on \Device\RaidPort2 during the 2026-09-14 session, backed by months of - historical Event 11 and Event 129 activity. The immediate priority is - preservation of data followed by physical M.2 inspection/reseat and controlled - device-versus-slot isolation. The firmware NVRAM/CMOS and TPM/Measured Boot - findings remain unresolved parallel tracks and should not yet be assumed to - share the same root cause. \ No newline at end of file +#requires -Version 5.1 + +<# +WindowsMaintenanceReport.ps1 + +Produces a structured JSON report instead of a human-formatted TXT report. + +Modes: + Default Compact maintenance snapshot + -Mid Hardware/software/startup/driver inventory + -Full Everything, including networking, event logs, processes, + firewall, devices, DISM and SFC verification. + +Examples: + .\WindowsMaintenanceReport.ps1 + .\WindowsMaintenanceReport.ps1 -Mid + .\WindowsMaintenanceReport.ps1 -Full + .\WindowsMaintenanceReport.ps1 -Mid -OutputDirectory C:\Temp + .\WindowsMaintenanceReport.ps1 -Full -EventLogDays 30 + +The report is UTF-8 JSON and is designed to be both human-readable and +machine-readable. PowerShell 5.1 is supported without extra modules. +#> + +[CmdletBinding()] +param( + [switch]$Mid, + [switch]$Full, + + [string]$OutputDirectory = '', + + [ValidateRange(1, 3650)] + [int]$EventLogDays = 7, + + [ValidateRange(1, 5000)] + [int]$MaxEventErrors = 100, + + [ValidateRange(3, 100)] + [int]$JsonDepth = 12 +) + +$ErrorActionPreference = 'Continue' + +if ($Mid -and $Full) { + throw 'Choose either -Mid or -Full, not both.' +} + +function Test-IsAdministrator { + try { + $identity = [Security.Principal.WindowsIdentity]::GetCurrent() + $principal = New-Object Security.Principal.WindowsPrincipal($identity) + return $principal.IsInRole( + [Security.Principal.WindowsBuiltInRole]::Administrator + ) + } + catch { + return $false + } +} + +function Test-DirectoryWritable { + param([string]$Path) + + try { + if (-not (Test-Path -LiteralPath $Path)) { + New-Item -ItemType Directory -Path $Path -Force -ErrorAction Stop | Out-Null + } + + $testFile = Join-Path $Path ( + '.winreport_write_test_' + + [guid]::NewGuid().ToString('N') + + '.tmp' + ) + + [System.IO.File]::WriteAllText($testFile, 'test') + Remove-Item -LiteralPath $testFile -Force -ErrorAction SilentlyContinue + return $true + } + catch { + return $false + } +} + +function Get-InstalledPrograms { + $paths = @( + 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*', + 'HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*', + 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*' + ) + + Get-ItemProperty $paths -ErrorAction SilentlyContinue | + Where-Object { $_.DisplayName } | + Select-Object DisplayName, DisplayVersion, Publisher, + InstallDate, InstallLocation | + Sort-Object DisplayName -Unique +} + +function Get-StartupRegistryEntries { + $startupKeys = @( + 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Run', + 'HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce', + 'HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Run', + 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run', + 'HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce' + ) + + foreach ($key in $startupKeys) { + if (Test-Path $key) { + $item = Get-ItemProperty $key -ErrorAction SilentlyContinue + + foreach ($property in $item.PSObject.Properties) { + if ($property.Name -notlike 'PS*') { + [pscustomobject][ordered]@{ + registry_path = $key + name = $property.Name + value = [string]$property.Value + } + } + } + } + } +} + +function Get-ProblemDevices { + if (Get-Command Get-PnpDevice -ErrorAction SilentlyContinue) { + Get-PnpDevice -PresentOnly -ErrorAction SilentlyContinue | + Where-Object { $_.Status -ne 'OK' } | + Select-Object Status, Class, FriendlyName, InstanceId + } + else { + Get-CimInstance Win32_PnPEntity -ErrorAction SilentlyContinue | + Where-Object { $_.ConfigManagerErrorCode -ne 0 } | + Select-Object Name, PNPClass, ConfigManagerErrorCode, DeviceID + } +} + +function Invoke-ReportSection { + param( + [Parameter(Mandatory=$true)] + [string]$Name, + + [Parameter(Mandatory=$true)] + [scriptblock]$Script, + + [switch]$Quiet + ) + + if (-not $Quiet) { + Write-Host ('Collecting: ' + $Name) + } + + try { + $data = @(& $Script) + + return [pscustomobject][ordered]@{ + status = 'ok' + count = $data.Count + data = $data + error = $null + } + } + catch { + return [pscustomobject][ordered]@{ + status = 'error' + count = 0 + data = @() + error = $_.Exception.Message + } + } +} + +function New-SkippedSection { + param([string]$Reason) + + [pscustomobject][ordered]@{ + status = 'skipped' + count = 0 + data = @() + error = $Reason + } +} + +function New-UnavailableSection { + param([string]$Reason) + + [pscustomobject][ordered]@{ + status = 'unavailable' + count = 0 + data = @() + error = $Reason + } +} + +function Get-StorageReport { + param([bool]$IsAdmin) + + $logical = @( + Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3" | + Select-Object DeviceID, VolumeName, FileSystem, + @{Name='size_gb';Expression={[math]::Round($_.Size / 1GB, 2)}}, + @{Name='free_gb';Expression={[math]::Round($_.FreeSpace / 1GB, 2)}}, + @{Name='free_percent';Expression={ + if ($_.Size) { + [math]::Round(($_.FreeSpace / $_.Size) * 100, 1) + } + else { + $null + } + }} + ) + + $physical = @( + Get-CimInstance Win32_DiskDrive | + Select-Object Model, InterfaceType, MediaType, + @{Name='size_gb';Expression={[math]::Round($_.Size / 1GB, 2)}}, + FirmwareRevision, SerialNumber, Status, DeviceID, Index + ) + + $storageHealth = @() + $reliability = @() + + if (Get-Command Get-PhysicalDisk -ErrorAction SilentlyContinue) { + try { + $physicalDisks = @(Get-PhysicalDisk -ErrorAction Stop) + + $storageHealth = @( + $physicalDisks | + Select-Object FriendlyName, MediaType, HealthStatus, + OperationalStatus, + @{Name='size_gb';Expression={[math]::Round($_.Size / 1GB, 2)}}, + DeviceId, BusType + ) + + if ($IsAdmin) { + foreach ($disk in $physicalDisks) { + try { + $counter = $disk | + Get-StorageReliabilityCounter -ErrorAction Stop | + Select-Object Temperature, Wear, ReadErrorsTotal, + WriteErrorsTotal, PowerOnHours + + $reliability += [pscustomobject][ordered]@{ + disk = $disk.FriendlyName + status = 'ok' + data = $counter + error = $null + } + } + catch { + $reliability += [pscustomobject][ordered]@{ + disk = $disk.FriendlyName + status = 'unavailable' + data = $null + error = $_.Exception.Message + } + } + } + } + } + catch { + $storageHealth = @( + [pscustomobject][ordered]@{ + status = 'unavailable' + error = $_.Exception.Message + } + ) + } + } + + [pscustomobject][ordered]@{ + logical_volumes = $logical + physical_disks = $physical + storage_health = $storageHealth + reliability_counters = $reliability + reliability_requires_admin = $true + } +} + +function Get-DefenderReport { + if (-not (Get-Command Get-MpComputerStatus -ErrorAction SilentlyContinue)) { + return [pscustomobject][ordered]@{ + available = $false + error = 'Microsoft Defender cmdlets unavailable.' + } + } + + try { + $def = Get-MpComputerStatus -ErrorAction Stop + + return $def | + Select-Object AntivirusEnabled, AntispywareEnabled, + RealTimeProtectionEnabled, BehaviorMonitorEnabled, + IoavProtectionEnabled, NISEnabled, + AntivirusSignatureLastUpdated, + AntispywareSignatureLastUpdated, + QuickScanAge, FullScanAge + } + catch { + return [pscustomobject][ordered]@{ + available = $false + error = $_.Exception.Message + } + } +} + +function Invoke-NativeCommand { + param( + [Parameter(Mandatory=$true)] + [string]$FilePath, + + [string[]]$Arguments = @() + ) + + try { + $output = @(& $FilePath @Arguments 2>&1 | ForEach-Object { [string]$_ }) + $exitCode = $LASTEXITCODE + + [pscustomobject][ordered]@{ + executable = $FilePath + arguments = $Arguments + exit_code = $exitCode + output = $output + } + } + catch { + [pscustomobject][ordered]@{ + executable = $FilePath + arguments = $Arguments + exit_code = $null + output = @() + error = $_.Exception.Message + } + } +} + +$isAdmin = Test-IsAdministrator + +if ([string]::IsNullOrWhiteSpace($OutputDirectory)) { + $candidate = (Get-Location).Path + + if (Test-DirectoryWritable $candidate) { + $OutputDirectory = $candidate + } + elseif (Test-DirectoryWritable $env:TEMP) { + $OutputDirectory = $env:TEMP + } + else { + throw 'Could not find a writable output directory.' + } +} +elseif (-not (Test-DirectoryWritable $OutputDirectory)) { + throw "Output directory is not writable: $OutputDirectory" +} + +$mode = 'Compact' +if ($Mid) { $mode = 'Mid' } +if ($Full) { $mode = 'Full' } + +$startedAt = Get-Date +$timestamp = $startedAt.ToString('yyyyMMdd_HHmmss') +$computerName = $env:COMPUTERNAME +$reportName = 'windows_system_report_' + $computerName + '_' + $timestamp + '.json' +$reportPath = Join-Path $OutputDirectory $reportName + +$report = [ordered]@{ + schema_version = 1 + report_type = 'windows_system_maintenance' + mode = $mode + generated_at = $startedAt.ToString('o') + completed_at = $null + + host = [ordered]@{ + computer_name = $computerName + user_name = $env:USERNAME + administrator = $isAdmin + powershell_version = [string]$PSVersionTable.PSVersion + } + + parameters = [ordered]@{ + event_log_days = $EventLogDays + max_event_errors = $MaxEventErrors + } + + warnings = @() + summary = $null + sections = [ordered]@{} +} + +if (-not $isAdmin) { + $report.warnings += 'Script is not elevated. Admin-only diagnostics are skipped.' +} + +if ($mode -eq 'Compact') { + Write-Host 'Collecting compact Windows maintenance report...' + + $os = Get-CimInstance Win32_OperatingSystem + $system = Get-CimInstance Win32_ComputerSystem + $bios = Get-CimInstance Win32_BIOS + $cpu = Get-CimInstance Win32_Processor | Select-Object -First 1 + $gpus = @(Get-CimInstance Win32_VideoController -ErrorAction SilentlyContinue) + $logicalDisks = @(Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3") + $programs = @(Get-InstalledPrograms) + $appx = @(Get-AppxPackage -ErrorAction SilentlyContinue) + $startupRegistry = @(Get-StartupRegistryEntries) + $startupCommands = @(Get-CimInstance Win32_StartupCommand -ErrorAction SilentlyContinue) + $autoServices = @( + Get-CimInstance Win32_Service -ErrorAction SilentlyContinue | + Where-Object { $_.StartMode -eq 'Auto' } + ) + $stoppedAuto = @($autoServices | Where-Object { $_.State -ne 'Running' }) + $problemDevices = @(Get-ProblemDevices) + $latestHotfix = Get-HotFix -ErrorAction SilentlyContinue | + Sort-Object InstalledOn -Descending | + Select-Object -First 1 + + $uptime = (Get-Date) - $os.LastBootUpTime + + $diskSummary = @( + $logicalDisks | ForEach-Object { + [pscustomobject][ordered]@{ + drive = $_.DeviceID + volume_name = $_.VolumeName + filesystem = $_.FileSystem + size_gb = if ($_.Size) {[math]::Round($_.Size / 1GB, 2)} else {$null} + free_gb = if ($_.FreeSpace -ne $null) {[math]::Round($_.FreeSpace / 1GB, 2)} else {$null} + free_percent = if ($_.Size) {[math]::Round(($_.FreeSpace / $_.Size) * 100, 1)} else {$null} + } + } + ) + + $diskHealth = @() + if (Get-Command Get-PhysicalDisk -ErrorAction SilentlyContinue) { + try { + $diskHealth = @( + Get-PhysicalDisk -ErrorAction Stop | + Select-Object FriendlyName, MediaType, HealthStatus, + OperationalStatus, + @{Name='size_gb';Expression={[math]::Round($_.Size / 1GB, 2)}} + ) + } + catch { + $report.warnings += ('Physical disk health unavailable: ' + $_.Exception.Message) + } + } + + $defender = Get-DefenderReport + + $report.summary = [ordered]@{ + system = [ordered]@{ + manufacturer = $system.Manufacturer + model = $system.Model + system_type = $system.SystemType + } + + operating_system = [ordered]@{ + caption = $os.Caption + version = $os.Version + build_number = $os.BuildNumber + architecture = $os.OSArchitecture + install_date = $os.InstallDate + last_boot = $os.LastBootUpTime + } + + bios = [ordered]@{ + manufacturer = $bios.Manufacturer + name = $bios.Name + smbios_version = $bios.SMBIOSBIOSVersion + release_date = $bios.ReleaseDate + serial_number = $bios.SerialNumber + } + + cpu = [ordered]@{ + name = $cpu.Name + manufacturer = $cpu.Manufacturer + cores = $cpu.NumberOfCores + logical_processors = $cpu.NumberOfLogicalProcessors + max_clock_mhz = $cpu.MaxClockSpeed + } + + memory = [ordered]@{ + total_gb = [math]::Round($system.TotalPhysicalMemory / 1GB, 2) + free_gb = [math]::Round($os.FreePhysicalMemory / 1MB, 2) + } + + gpus = @( + $gpus | Select-Object Name, DriverVersion, VideoModeDescription + ) + + storage = [ordered]@{ + logical_volumes = $diskSummary + physical_health = $diskHealth + } + + software = [ordered]@{ + desktop_program_count = $programs.Count + appx_package_count = $appx.Count + } + + startup = [ordered]@{ + registry_entry_count = $startupRegistry.Count + command_count = $startupCommands.Count + } + + services = [ordered]@{ + automatic_count = $autoServices.Count + automatic_not_running = $stoppedAuto.Count + } + + devices = [ordered]@{ + problem_count = $problemDevices.Count + } + + latest_hotfix = if ($latestHotfix) { + [ordered]@{ + hotfix_id = $latestHotfix.HotFixID + description = $latestHotfix.Description + installed_by = $latestHotfix.InstalledBy + installed_on = $latestHotfix.InstalledOn + } + } + else { + $null + } + + defender = $defender + + uptime = [ordered]@{ + last_boot = $os.LastBootUpTime + days = $uptime.Days + hours = $uptime.Hours + minutes = $uptime.Minutes + } + } +} +else { + # ---------------------------------------------------------------------- + # MID + FULL COMMON SECTIONS + # ---------------------------------------------------------------------- + + $report.sections.operating_system = Invoke-ReportSection 'Operating system' { + Get-CimInstance Win32_OperatingSystem | + Select-Object Caption, Version, BuildNumber, OSArchitecture, + InstallDate, LastBootUpTime, LocalDateTime, + @{Name='total_memory_gb';Expression={[math]::Round($_.TotalVisibleMemorySize / 1MB, 2)}}, + @{Name='free_memory_gb';Expression={[math]::Round($_.FreePhysicalMemory / 1MB, 2)}} + } + + $report.sections.computer_system = Invoke-ReportSection 'Computer system' { + Get-CimInstance Win32_ComputerSystem | + Select-Object Manufacturer, Model, SystemType, + @{Name='total_physical_memory_gb';Expression={[math]::Round($_.TotalPhysicalMemory / 1GB, 2)}}, + Domain, PartOfDomain + } + + $report.sections.bios = Invoke-ReportSection 'BIOS' { + Get-CimInstance Win32_BIOS | + Select-Object Manufacturer, Name, SMBIOSBIOSVersion, + ReleaseDate, SerialNumber + } + + $report.sections.cpu = Invoke-ReportSection 'CPU' { + Get-CimInstance Win32_Processor | + Select-Object Name, Manufacturer, NumberOfCores, + NumberOfLogicalProcessors, MaxClockSpeed, + CurrentClockSpeed, LoadPercentage + } + + $report.sections.memory_modules = Invoke-ReportSection 'Memory modules' { + Get-CimInstance Win32_PhysicalMemory | + Select-Object BankLabel, DeviceLocator, + @{Name='capacity_gb';Expression={[math]::Round($_.Capacity / 1GB, 2)}}, + Speed, ConfiguredClockSpeed, Manufacturer, PartNumber + } + + $report.sections.motherboard = Invoke-ReportSection 'Motherboard' { + Get-CimInstance Win32_BaseBoard | + Select-Object Manufacturer, Product, Version, SerialNumber + } + + $report.sections.gpus = Invoke-ReportSection 'GPU / display adapters' { + Get-CimInstance Win32_VideoController | + Select-Object Name, DriverVersion, VideoModeDescription + } + + $report.sections.storage = Invoke-ReportSection 'Storage / free space / health' { + Get-StorageReport -IsAdmin $isAdmin + } + + $report.sections.installed_programs = Invoke-ReportSection 'Installed programs' { + Get-InstalledPrograms + } + + if (Get-Command Get-AppxPackage -ErrorAction SilentlyContinue) { + $report.sections.appx_packages = Invoke-ReportSection 'Microsoft Store / AppX packages' { + Get-AppxPackage -ErrorAction SilentlyContinue | + Select-Object Name, Version, Publisher, Architecture | + Sort-Object Name + } + } + else { + $report.sections.appx_packages = + New-UnavailableSection 'Get-AppxPackage is unavailable.' + } + + $report.sections.startup_registry = Invoke-ReportSection 'Startup registry locations' { + Get-StartupRegistryEntries | + Sort-Object registry_path, name + } + + $report.sections.automatic_services = Invoke-ReportSection 'Automatic services' { + Get-CimInstance Win32_Service | + Where-Object { $_.StartMode -eq 'Auto' } | + Select-Object Name, DisplayName, State, StartMode, StartName | + Sort-Object State, DisplayName + } + + $report.sections.signed_drivers = Invoke-ReportSection 'Signed drivers' { + Get-CimInstance Win32_PnPSignedDriver | + Where-Object { $_.DeviceName } | + Select-Object DeviceName, Manufacturer, DriverVersion, DriverDate | + Sort-Object DeviceName + } + + $report.sections.hotfixes = Invoke-ReportSection 'Windows updates / hotfixes' { + Get-HotFix -ErrorAction SilentlyContinue | + Sort-Object InstalledOn -Descending | + Select-Object HotFixID, Description, InstalledBy, InstalledOn + } + + $report.sections.defender = Invoke-ReportSection 'Windows Defender status' { + Get-DefenderReport + } + + if (Get-Command Get-ScheduledTask -ErrorAction SilentlyContinue) { + $report.sections.non_microsoft_scheduled_tasks = + Invoke-ReportSection 'Non-Microsoft scheduled tasks' { + Get-ScheduledTask -ErrorAction SilentlyContinue | + Where-Object { $_.TaskPath -notlike '\Microsoft\*' } | + Select-Object TaskName, TaskPath, State | + Sort-Object TaskPath, TaskName + } + } + else { + $report.sections.non_microsoft_scheduled_tasks = + New-UnavailableSection 'Get-ScheduledTask is unavailable.' + } + + # ---------------------------------------------------------------------- + # FULL-ONLY SECTIONS + # ---------------------------------------------------------------------- + if ($Full) { + $report.sections.uptime = Invoke-ReportSection 'Uptime' { + $os = Get-CimInstance Win32_OperatingSystem + $uptime = (Get-Date) - $os.LastBootUpTime + + [pscustomobject][ordered]@{ + last_boot = $os.LastBootUpTime + days = $uptime.Days + hours = $uptime.Hours + minutes = $uptime.Minutes + } + } + + $report.sections.startup_programs = Invoke-ReportSection 'Startup programs' { + Get-CimInstance Win32_StartupCommand | + Select-Object Name, Command, Location, User | + Sort-Object Name + } + + $report.sections.startup_folders = Invoke-ReportSection 'Startup folders' { + $folders = @( + (Join-Path $env:APPDATA 'Microsoft\Windows\Start Menu\Programs\Startup'), + (Join-Path $env:ProgramData 'Microsoft\Windows\Start Menu\Programs\Startup') + ) + + foreach ($folder in $folders) { + $exists = Test-Path $folder + $items = @() + + if ($exists) { + $items = @( + Get-ChildItem $folder -Force -ErrorAction SilentlyContinue | + Select-Object Name, FullName, LastWriteTime + ) + } + + [pscustomobject][ordered]@{ + path = $folder + exists = $exists + items = $items + } + } + } + + $report.sections.automatic_services_not_running = + Invoke-ReportSection 'Automatic services not running' { + Get-CimInstance Win32_Service | + Where-Object { + $_.StartMode -eq 'Auto' -and $_.State -ne 'Running' + } | + Select-Object Name, DisplayName, State, StartMode + } + + $report.sections.problem_devices = Invoke-ReportSection 'Devices with problems' { + Get-ProblemDevices + } + + if (Get-Command Get-NetFirewallProfile -ErrorAction SilentlyContinue) { + $report.sections.firewall_profiles = Invoke-ReportSection 'Firewall profiles' { + Get-NetFirewallProfile -ErrorAction SilentlyContinue | + Select-Object Name, Enabled, DefaultInboundAction, + DefaultOutboundAction + } + } + else { + $report.sections.firewall_profiles = + New-UnavailableSection 'Get-NetFirewallProfile is unavailable.' + } + + if (Get-Command Get-NetAdapter -ErrorAction SilentlyContinue) { + $report.sections.network_adapters = Invoke-ReportSection 'Network adapters' { + Get-NetAdapter -ErrorAction SilentlyContinue | + Select-Object Name, InterfaceDescription, Status, + LinkSpeed, MacAddress + } + } + else { + $report.sections.network_adapters = + New-UnavailableSection 'Get-NetAdapter is unavailable.' + } + + $report.sections.ip_configuration = Invoke-ReportSection 'IP configuration' { + if (Get-Command Get-NetIPConfiguration -ErrorAction SilentlyContinue) { + Get-NetIPConfiguration -ErrorAction SilentlyContinue | + ForEach-Object { + [pscustomobject][ordered]@{ + interface_alias = $_.InterfaceAlias + interface_index = $_.InterfaceIndex + ipv4_addresses = @($_.IPv4Address | ForEach-Object { $_.IPAddress }) + ipv6_addresses = @($_.IPv6Address | ForEach-Object { $_.IPAddress }) + ipv4_gateway = @($_.IPv4DefaultGateway | ForEach-Object { $_.NextHop }) + ipv6_gateway = @($_.IPv6DefaultGateway | ForEach-Object { $_.NextHop }) + dns_servers = @($_.DNSServer.ServerAddresses) + } + } + } + else { + Invoke-NativeCommand -FilePath 'ipconfig.exe' -Arguments @('/all') + } + } + + if (Get-Command Get-DnsClientServerAddress -ErrorAction SilentlyContinue) { + $report.sections.dns_servers = Invoke-ReportSection 'DNS servers' { + Get-DnsClientServerAddress -ErrorAction SilentlyContinue | + Where-Object { $_.ServerAddresses.Count -gt 0 } | + Select-Object InterfaceAlias, AddressFamily, + @{Name='servers';Expression={@($_.ServerAddresses)}} + } + } + else { + $report.sections.dns_servers = + New-UnavailableSection 'Get-DnsClientServerAddress is unavailable.' + } + + if (Get-Command Get-NetTCPConnection -ErrorAction SilentlyContinue) { + $report.sections.active_tcp_listeners = + Invoke-ReportSection 'Active TCP listeners' { + Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue | + Select-Object LocalAddress, LocalPort, OwningProcess | + Sort-Object LocalPort + } + } + else { + $report.sections.active_tcp_listeners = + Invoke-ReportSection 'Active TCP listeners' { + Invoke-NativeCommand -FilePath 'netstat.exe' -Arguments @('-ano') + } + } + + $report.sections.power_plan = Invoke-ReportSection 'Power plan' { + Invoke-NativeCommand -FilePath 'powercfg.exe' -Arguments @('/getactivescheme') + } + + $report.sections.battery = Invoke-ReportSection 'Battery' { + Get-CimInstance Win32_Battery -ErrorAction SilentlyContinue | + Select-Object Name, Status, EstimatedChargeRemaining, + EstimatedRunTime, BatteryStatus + } + + $report.sections.top_processes_by_memory = + Invoke-ReportSection 'Top processes by memory' { + Get-Process | + Sort-Object WorkingSet64 -Descending | + Select-Object -First 30 ProcessName, Id, + @{Name='memory_mb';Expression={[math]::Round($_.WorkingSet64 / 1MB, 1)}}, + CPU + } + + $start = (Get-Date).AddDays(-$EventLogDays) + + $report.sections.recent_system_errors = + Invoke-ReportSection ('Recent system errors - last ' + $EventLogDays + ' days') { + Get-WinEvent -FilterHashtable @{ + LogName = 'System' + Level = 2 + StartTime = $start + } -ErrorAction SilentlyContinue | + Select-Object -First $MaxEventErrors TimeCreated, Id, + ProviderName, Message + } + + $report.sections.recent_application_errors = + Invoke-ReportSection ('Recent application errors - last ' + $EventLogDays + ' days') { + Get-WinEvent -FilterHashtable @{ + LogName = 'Application' + Level = 2 + StartTime = $start + } -ErrorAction SilentlyContinue | + Select-Object -First $MaxEventErrors TimeCreated, Id, + ProviderName, Message + } + + if ($isAdmin) { + $report.sections.component_store = + Invoke-ReportSection 'Windows component store status' { + Invoke-NativeCommand -FilePath 'DISM.exe' -Arguments @( + '/Online', + '/Cleanup-Image', + '/CheckHealth' + ) + } + + $report.sections.system_file_check = + Invoke-ReportSection 'System file check - verify only' { + $tempSfc = Join-Path $env:TEMP ( + 'winreport_sfc_' + + [guid]::NewGuid().ToString('N') + + '.txt' + ) + + try { + cmd.exe /c "sfc.exe /verifyonly > `"$tempSfc`" 2>&1" + $exitCode = $LASTEXITCODE + $lines = @() + + if (Test-Path $tempSfc) { + $bytes = [System.IO.File]::ReadAllBytes($tempSfc) + $text = [System.Text.Encoding]::Unicode.GetString($bytes) + $lines = @( + $text.Trim([char]0) -split "`r?`n" | + Where-Object { $_ -ne '' } + ) + } + + [pscustomobject][ordered]@{ + executable = 'sfc.exe' + arguments = @('/verifyonly') + exit_code = $exitCode + output = $lines + } + } + finally { + Remove-Item $tempSfc -Force -ErrorAction SilentlyContinue + } + } + } + else { + $report.sections.component_store = + New-SkippedSection 'DISM /CheckHealth requires an elevated session.' + + $report.sections.system_file_check = + New-SkippedSection 'sfc /verifyonly requires an elevated session.' + } + + $report.sections.important_directories = + Invoke-ReportSection 'Important directories' { + [pscustomobject][ordered]@{ + windows_directory = $env:WINDIR + system_drive = $env:SystemDrive + program_files = $env:ProgramFiles + program_files_x86 = [Environment]::GetEnvironmentVariable('ProgramFiles(x86)') + program_data = $env:ProgramData + user_profile = $env:USERPROFILE + temp = $env:TEMP + } + } + } +} + +$report.completed_at = (Get-Date).ToString('o') + +$json = $report | ConvertTo-Json -Depth $JsonDepth + +# UTF-8 without BOM, matching the original script's encoding choice. +$utf8NoBom = New-Object System.Text.UTF8Encoding($false) +[System.IO.File]::WriteAllText($reportPath, $json, $utf8NoBom) + +Write-Host '' +Write-Host ('Report mode: ' + $mode) +Write-Host ('Saved JSON report to: ' + $reportPath) + +# Return the path as the script result, useful for automation. +$reportPath \ No newline at end of file