WinDiagnostics/WindowsMaintenanceReport.ps1

1030 lines
39 KiB
PowerShell

#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,
driver stores, kernel/filter drivers, services, virtualization,
storage/PnP, Code Integrity, reliability and crash metadata.
Includes read-only DISM and SFC verification when elevated.
All modes support non-administrator sessions. Restricted or unavailable checks
are recorded in the JSON and collection continues. Full mode collects evidence;
it does not automatically diagnose, repair, update, disable, uninstall or replace
drivers or devices. Schema version 2 adds collection status and bounded events.
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\*'
)
$(foreach ($path in $paths) {
$parent = Split-Path $path -Parent
if (Test-Path -LiteralPath $parent -ErrorAction Stop) {
Get-ItemProperty $path -ErrorAction Stop
}
}) | 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 Stop
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 Stop |
Where-Object { $_.Status -ne 'OK' -or ($null -ne $_.Problem -and [int]$_.Problem -ne 0) -or ($null -ne $_.ConfigManagerErrorCode -and $_.ConfigManagerErrorCode -ne 0) } |
Select-Object Status, Class, FriendlyName, InstanceId, Problem, ConfigManagerErrorCode
}
else {
Get-CimInstance Win32_PnPEntity -ErrorAction Stop |
Where-Object { $_.ConfigManagerErrorCode -ne 0 } |
Select-Object Status, @{Name='Class';Expression={$_.PNPClass}},
@{Name='FriendlyName';Expression={$_.Name}},
@{Name='InstanceId';Expression={$_.DeviceID}}, Problem, ConfigManagerErrorCode
}
}
function Invoke-ReportSection {
param(
[Parameter(Mandatory=$true)]
[string]$Name,
[Parameter(Mandatory=$true)]
[scriptblock]$Script,
[switch]$Quiet
)
if (-not $Quiet) {
Write-Host ('Collecting: ' + $Name)
}
try {
$ErrorActionPreference = 'Stop'
$data = @(& $Script)
$nativeFailures = @($data | Where-Object {
$_.PSObject.Properties['exit_code'] -and ($null -eq $_.exit_code -or $_.exit_code -ne 0)
})
return [pscustomobject][ordered]@{
status = if ($nativeFailures.Count) { 'unavailable' } else { 'ok' }
count = $data.Count
data = $data
error = if ($nativeFailures.Count) { 'Native command failed; see exit_code and output.' } else { $null }
}
}
catch {
return [pscustomobject][ordered]@{
status = 'unavailable'
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 (-not $IsAdmin) {
$reliability = @(New-SkippedSection 'Administrator privileges required.')
}
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 {
# Windows PowerShell can emit native stderr as non-terminating errors.
$ErrorActionPreference = 'Continue'
$null = Get-Command $FilePath -CommandType Application -ErrorAction Stop
$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)) {
# Resolve the Windows Documents folder, including redirected/OneDrive paths.
$candidate = [Environment]::GetFolderPath(
[Environment+SpecialFolder]::MyDocuments,
[Environment+SpecialFolderOption]::DoNotVerify
)
if (-not [string]::IsNullOrWhiteSpace($candidate) -and
(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 = 2
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...'
function Get-CompactData {
param([string]$Name, [scriptblock]$Script)
$section = Invoke-ReportSection $Name $Script -Quiet
# Keep Compact small and avoid serializing raw CIM object graphs.
$report.sections[$Name] = [pscustomobject][ordered]@{
status = $section.status
count = $section.count
error = $section.error
}
if ($section.status -ne 'ok') {
$report.warnings += ($Name + ': ' + $section.error)
}
$section.data
}
$os = Get-CompactData 'operating_system' { Get-CimInstance Win32_OperatingSystem }
$system = Get-CompactData 'computer_system' { Get-CimInstance Win32_ComputerSystem }
$bios = Get-CompactData 'bios' { Get-CimInstance Win32_BIOS }
$cpu = Get-CompactData 'cpu' { Get-CimInstance Win32_Processor | Select-Object -First 1 }
$gpus = @(Get-CompactData 'gpus' { Get-CimInstance Win32_VideoController })
$logicalDisks = @(Get-CompactData 'logical_disks' { Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3" })
$programs = @(Get-CompactData 'installed_programs' { Get-InstalledPrograms })
$appx = @(Get-CompactData 'appx_packages' { Get-AppxPackage -ErrorAction Stop })
$startupRegistry = @(Get-CompactData 'startup_registry' { Get-StartupRegistryEntries })
$startupCommands = @(Get-CompactData 'startup_programs' { Get-CimInstance Win32_StartupCommand })
$autoServices = @(Get-CompactData 'automatic_services' {
Get-CimInstance Win32_Service | Where-Object { $_.StartMode -eq 'Auto' }
})
$stoppedAuto = @($autoServices | Where-Object { $_.State -ne 'Running' })
$problemDevices = @(Get-CompactData 'problem_devices' { Get-ProblemDevices })
$latestHotfix = Get-CompactData 'latest_hotfix' {
Get-HotFix -ErrorAction Stop | Sort-Object InstalledOn -Descending | Select-Object -First 1
}
$uptime = if ($os.LastBootUpTime) { (Get-Date) - $os.LastBootUpTime } else { $null }
$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 = $(if ($null -ne $system.TotalPhysicalMemory) { [math]::Round($system.TotalPhysicalMemory / 1GB, 2) } else { $null })
free_gb = $(if ($null -ne $os.FreePhysicalMemory) { [math]::Round($os.FreePhysicalMemory / 1MB, 2) } else { $null })
}
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 Stop |
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 |
Select-Object DeviceName, DeviceClass, Manufacturer, DriverProviderName,
DriverVersion, DriverDate, InfName, IsSigned, Signer, DeviceID |
Sort-Object DeviceName
}
$report.sections.hotfixes = Invoke-ReportSection 'Windows updates / hotfixes' {
Get-HotFix -ErrorAction Stop |
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 Stop |
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.system_drivers = Invoke-ReportSection 'System drivers' {
Get-CimInstance Win32_SystemDriver |
Select-Object Name, DisplayName, State, StartMode, PathName, ServiceType
}
$report.sections.services = Invoke-ReportSection 'Services' {
Get-CimInstance Win32_Service |
Select-Object Name, DisplayName, State, StartMode, StartName, PathName
}
$report.sections.storage_disks = Invoke-ReportSection 'Storage disks' {
Get-Disk -ErrorAction Stop | Select-Object Number, FriendlyName, SerialNumber,
BusType, OperationalStatus, HealthStatus, PartitionStyle, Size,
IsBoot, IsSystem, FirmwareVersion, Location
}
$report.sections.storage_pnp_devices = Invoke-ReportSection 'Storage PnP devices' {
$classes = @('SCSIAdapter', 'HDC', 'DiskDrive', 'Storage', 'System')
if (Get-Command Get-PnpDevice -ErrorAction SilentlyContinue) {
Get-PnpDevice -PresentOnly -ErrorAction Stop |
Where-Object { $_.Class -in $classes } |
Select-Object Status, Class, FriendlyName, InstanceId, Problem, ConfigManagerErrorCode
}
else {
Get-CimInstance Win32_PnPEntity | Where-Object { $_.Present -and $_.PNPClass -in $classes } |
Select-Object Status, @{Name='Class';Expression={$_.PNPClass}},
@{Name='FriendlyName';Expression={$_.Name}},
@{Name='InstanceId';Expression={$_.DeviceID}}, Problem, ConfigManagerErrorCode
}
}
$nativeInventories = @(
@{ Key='driver_store'; Exe='pnputil.exe'; Args=@('/enum-drivers'); Admin=$false },
@{ Key='filter_drivers'; Exe='fltmc.exe'; Args=@('filters'); Admin=$true },
@{ Key='filter_instances'; Exe='fltmc.exe'; Args=@('instances'); Admin=$true },
@{ Key='upper_filters'; Exe='reg.exe'; Args=@('query', 'HKLM\SYSTEM\CurrentControlSet\Control\Class', '/s', '/v', 'UpperFilters'); Admin=$false },
@{ Key='lower_filters'; Exe='reg.exe'; Args=@('query', 'HKLM\SYSTEM\CurrentControlSet\Control\Class', '/s', '/v', 'LowerFilters'); Admin=$false },
@{ Key='boot_configuration'; Exe='bcdedit.exe'; Args=@('/enum', 'all'); Admin=$true }
)
foreach ($inventory in $nativeInventories) {
if ($inventory.Admin -and -not $isAdmin) {
$report.sections[$inventory.Key] = New-SkippedSection 'Administrator privileges required.'
}
else {
$report.sections[$inventory.Key] = Invoke-ReportSection $inventory.Key {
Invoke-NativeCommand -FilePath $inventory.Exe -Arguments $inventory.Args
}
}
}
if ($isAdmin) {
$report.sections.enabled_windows_features = Invoke-ReportSection 'Enabled Windows features' {
Get-WindowsOptionalFeature -Online -ErrorAction Stop |
Where-Object { $_.State -eq 'Enabled' } | Select-Object FeatureName, State
}
}
else {
$report.sections.enabled_windows_features = New-SkippedSection 'Administrator privileges required.'
}
$report.sections.reliability_records = Invoke-ReportSection 'Reliability records' {
$since = (Get-Date).ToUniversalTime().AddDays(-$EventLogDays).ToString('yyyyMMddHHmmss.000000')
Get-CimInstance Win32_ReliabilityRecords -Filter ("TimeGenerated >= '" + $since + "+000'") |
Select-Object TimeGenerated, SourceName, EventIdentifier, ProductName, Message
}
$report.sections.minidumps = Invoke-ReportSection 'Crash dump metadata' {
$dumpDirectory = Join-Path $env:SystemRoot 'Minidump'
if (Test-Path -LiteralPath $dumpDirectory -ErrorAction Stop) {
Get-ChildItem -LiteralPath $dumpDirectory -File -ErrorAction Stop |
Select-Object Name, Length, CreationTime, LastWriteTime
}
$memoryDump = Join-Path $env:SystemRoot 'MEMORY.DMP'
if (Test-Path -LiteralPath $memoryDump -ErrorAction Stop) {
Get-Item -LiteralPath $memoryDump -ErrorAction Stop |
Select-Object Name, Length, CreationTime, LastWriteTime
}
}
$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 -ErrorAction Stop
$items = @()
if ($exists) {
$items = @(
Get-ChildItem $folder -Force -ErrorAction Stop |
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 Stop |
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 Stop |
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 Stop |
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 Stop |
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 Stop |
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 Stop |
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)
foreach ($log in @(
@{ Key='recent_system_events'; Name='System'; Levels=@(1,2,3) },
@{ Key='recent_application_events'; Name='Application'; Levels=@(1,2,3) },
@{ Key='code_integrity'; Name='Microsoft-Windows-CodeIntegrity/Operational'; Levels=@(1,2,3,4,5) }
)) {
$section = Invoke-ReportSection $log.Name {
$logInfo = Get-WinEvent -ListLog $log.Name -ErrorAction Stop
if (-not $logInfo.IsEnabled) { throw 'Event log is disabled.' }
try {
Get-WinEvent -FilterHashtable @{
LogName=$log.Name; Level=$log.Levels; StartTime=$start
} -MaxEvents ($MaxEventErrors + 1) -ErrorAction Stop |
Select-Object TimeCreated, ProviderName, Id, Level, LevelDisplayName, Message
}
catch {
if ($_.FullyQualifiedErrorId -notlike 'NoMatchingEventsFound*') { throw }
}
}
$truncated = $section.count -gt $MaxEventErrors
if ($truncated) {
$section.data = @($section.data | Select-Object -First $MaxEventErrors)
$section.count = $section.data.Count
}
$section | Add-Member -NotePropertyName truncated -NotePropertyValue $truncated
$section | Add-Member -NotePropertyName limit -NotePropertyValue $MaxEventErrors
$report.sections[$log.Key] = $section
}
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
}
}
}
}
if ($Full) {
$report.diagnostic_collection = [ordered]@{}
foreach ($key in $report.sections.Keys) {
$report.diagnostic_collection[$key] = ($report.sections[$key].status -eq 'ok')
}
}
$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