From 33c94886a4e54b262b19c2382f702cdda7ed90a5 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 4 Sep 2026 13:02:41 +0200 Subject: [PATCH] Trying updated script --- WindowsMaintenanceReport.ps1 | 953 +++++++++++++++++++++-------------- 1 file changed, 578 insertions(+), 375 deletions(-) diff --git a/WindowsMaintenanceReport.ps1 b/WindowsMaintenanceReport.ps1 index 92fc383..5e8110d 100644 --- a/WindowsMaintenanceReport.ps1 +++ b/WindowsMaintenanceReport.ps1 @@ -1,193 +1,386 @@ +#requires -Version 5.1 + <# -.SYNOPSIS - Generates a Windows system and maintenance report. +WindowsMaintenanceReport.ps1 -.DESCRIPTION - Dependency-free, non-GUI Windows inventory and diagnostics script. +Three report levels: - It collects: - - OS, BIOS, motherboard, CPU, RAM, GPU - - Disks, free space, physical disk health - - Installed desktop programs and AppX packages - - Startup programs, Run registry entries, startup folders - - Services and stopped automatic services - - Drivers and problem devices - - Windows hotfixes - - Defender and Firewall status - - Network adapters, IP/DNS config, listening TCP ports - - Power plan and battery info - - Scheduled tasks - - Top processes by memory - - Recent System/Application event log errors - - DISM component-store health - - SFC verify-only status + Default Compact maintenance snapshot (target: under 20 lines) + -Mid Useful hardware/software/startup/driver inventory + -Full Everything, including networking, event logs, processes, + firewall, devices, DISM and SFC verification. - The script is intended to be READ-ONLY. It does not repair, uninstall, - disable, delete, or modify system settings. +Examples: -.PARAMETER OutputDirectory - Directory in which to write the report. - Default: current working directory. - -.PARAMETER EventLogDays - Number of days of System/Application errors to include. - Default: 7. - -.PARAMETER MaxEventErrors - Maximum number of errors to include from each event log. - Default: 100. - -.PARAMETER InstallCommand - Creates a winreport.cmd launcher next to this script. - If the script folder is on PATH, you can then run: - winreport - -.EXAMPLE .\WindowsMaintenanceReport.ps1 + .\WindowsMaintenanceReport.ps1 -Mid + .\WindowsMaintenanceReport.ps1 -Full + .\WindowsMaintenanceReport.ps1 -Mid -OutputDirectory C:\Temp + .\WindowsMaintenanceReport.ps1 -Full -EventLogDays 30 -.EXAMPLE - .\WindowsMaintenanceReport.ps1 -OutputDirectory C:\Temp +Remote execution from a trusted URL: -.EXAMPLE - .\WindowsMaintenanceReport.ps1 -EventLogDays 30 -MaxEventErrors 250 + irm 'https://example/WindowsMaintenanceReport.ps1' | iex -.EXAMPLE - powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\WindowsMaintenanceReport.ps1 +For flags when executing downloaded source: -.EXAMPLE - .\WindowsMaintenanceReport.ps1 -InstallCommand + $src = irm 'https://example/WindowsMaintenanceReport.ps1' + & ([ScriptBlock]::Create($src)) -Mid -.NOTES - Recommended: run as Administrator for the most complete output. - - If execution policy blocks the script, use: - powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\WindowsMaintenanceReport.ps1 - - To call "winreport" from anywhere: - 1. Put this script in a permanent folder, e.g. C:\Tools\WinReport - 2. Run: - .\WindowsMaintenanceReport.ps1 -InstallCommand - 3. Add that folder to PATH - 4. Then use: - winreport +Administrator privileges are recommended but not required. +The script is read-only. Admin-only checks are skipped when unavailable. +Output streams live to the terminal and is simultaneously saved to a report. #> [CmdletBinding()] param( - [string]$OutputDirectory = (Get-Location).Path, + [switch]$Mid, + [switch]$Full, + + [string]$OutputDirectory = '', + [ValidateRange(1, 3650)] [int]$EventLogDays = 7, + [ValidateRange(1, 5000)] - [int]$MaxEventErrors = 100, - [switch]$InstallCommand + [int]$MaxEventErrors = 100 ) $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) + 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 Write-Both { + param( + [System.IO.StreamWriter]$Writer, + [string]$Text = '' + ) + + Write-Host $Text + $Writer.WriteLine($Text) + $Writer.Flush() +} + function Write-Section { param( - [Parameter(Mandatory)] [System.IO.StreamWriter]$Writer, - - [Parameter(Mandatory)] [string]$Title, - - [Parameter(Mandatory)] [scriptblock]$Script ) - $Writer.WriteLine() - $Writer.WriteLine(('=' * 80)) - $Writer.WriteLine($Title) - $Writer.WriteLine(('=' * 80)) + $separator = '=' * 80 + + Write-Both $Writer '' + Write-Both $Writer $separator + Write-Both $Writer $Title + Write-Both $Writer $separator try { - $result = & $Script 2>&1 | Out-String -Width 240 + & $Script 2>&1 | ForEach-Object { + $text = ($_ | Out-String -Width 240).TrimEnd() - if ([string]::IsNullOrWhiteSpace($result)) { - $Writer.WriteLine('(no output)') - } - else { - $Writer.WriteLine($result.TrimEnd()) + if (-not [string]::IsNullOrWhiteSpace($text)) { + Write-Both $Writer $text + } } } catch { - $Writer.WriteLine("ERROR: $($_.Exception.Message)") + Write-Both $Writer ('ERROR: ' + $_.Exception.Message) } } -function Install-WinReportCommand { - $scriptPath = $MyInvocation.PSCommandPath +function Get-InstalledPrograms { + $paths = @( + 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*', + 'HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*', + 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*' + ) - if (-not $scriptPath) { - throw 'Unable to determine current script path.' + 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*') { + New-Object PSObject -Property @{ + RegistryPath = $key + Name = $property.Name + Value = $property.Value + } + } + } + } + } +} + +function Get-ProblemDevices { + if (Get-Command Get-PnpDevice -ErrorAction SilentlyContinue) { + Get-PnpDevice -PresentOnly -ErrorAction SilentlyContinue | + Where-Object { $_.Status -ne 'OK' } + } + else { + Get-CimInstance Win32_PnPEntity -ErrorAction SilentlyContinue | + Where-Object { $_.ConfigManagerErrorCode -ne 0 } + } +} + +function Get-DiskHealthSummary { + if (-not (Get-Command Get-PhysicalDisk -ErrorAction SilentlyContinue)) { + return 'Unavailable' } - $scriptDir = Split-Path -Parent $scriptPath - $cmdPath = Join-Path $scriptDir 'winreport.cmd' - $scriptName = Split-Path -Leaf $scriptPath + try { + $physical = @(Get-PhysicalDisk -ErrorAction Stop) - $cmd = @" -@echo off -powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0$scriptName" %* -"@ + if ($physical.Count -eq 0) { + return 'No physical disks returned' + } - Set-Content -LiteralPath $cmdPath -Value $cmd -Encoding ASCII + $bad = @( + $physical | + Where-Object { + $_.HealthStatus -and + $_.HealthStatus -ne 'Healthy' + } + ) - Write-Host "Created launcher:" - Write-Host " $cmdPath" - Write-Host - Write-Host "If this folder is on PATH, you can run:" - Write-Host " winreport" + if ($bad.Count -eq 0) { + return 'Healthy (' + $physical.Count + ' disk(s))' + } + + return ( + ($bad | ForEach-Object { + $_.FriendlyName + ': ' + $_.HealthStatus + }) -join '; ' + ) + } + catch { + return 'Unavailable' + } } -if ($InstallCommand) { - Install-WinReportCommand - exit 0 +$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" } -if (-not (Test-Path -LiteralPath $OutputDirectory)) { - New-Item -ItemType Directory -Path $OutputDirectory -Force | Out-Null -} +$mode = 'Compact' +if ($Mid) { $mode = 'Mid' } +if ($Full) { $mode = 'Full' } -$timestamp = Get-Date -Format 'yyyyMMdd_HHmmss' +$timestamp = Get-Date -Format 'yyyyMMdd_HHmmss' $computerName = $env:COMPUTERNAME -$reportPath = Join-Path $OutputDirectory "windows_system_report_${computerName}_${timestamp}.txt" +$reportName = 'windows_system_report_' + $computerName + '_' + $timestamp + '.txt' +$reportPath = Join-Path $OutputDirectory $reportName -$utf8NoBom = New-Object System.Text.UTF8Encoding($false) -$writer = New-Object System.IO.StreamWriter($reportPath, $false, $utf8NoBom) +$encoding = New-Object System.Text.UTF8Encoding($false) +$writer = New-Object System.IO.StreamWriter($reportPath, $false, $encoding) try { - $writer.WriteLine('WINDOWS SYSTEM / MAINTENANCE REPORT') - $writer.WriteLine("Generated: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss K')") - $writer.WriteLine("Computer: $computerName") - $writer.WriteLine("User: $env:USERNAME") - $writer.WriteLine("Administrator: $(Test-IsAdministrator)") - $writer.WriteLine("PowerShell: $($PSVersionTable.PSVersion)") - $writer.WriteLine("Event log days: $EventLogDays") + # ---------------------------------------------------------------------- + # COMPACT DEFAULT + # ---------------------------------------------------------------------- + if (-not $Mid -and -not $Full) { + $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) + $disks = @(Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3") + $programs = @(Get-InstalledPrograms) + $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 + $ramTotalGB = [math]::Round($system.TotalPhysicalMemory / 1GB, 1) + $ramFreeGB = [math]::Round($os.FreePhysicalMemory / 1MB, 1) + + $gpuText = if ($gpus.Count -gt 0) { + ($gpus | ForEach-Object { $_.Name }) -join '; ' + } + else { + 'Unknown' + } + + $diskText = if ($disks.Count -gt 0) { + ($disks | ForEach-Object { + $size = [math]::Round($_.Size / 1GB, 0) + $free = [math]::Round($_.FreeSpace / 1GB, 0) + $pct = if ($_.Size) { + [math]::Round(($_.FreeSpace / $_.Size) * 100, 0) + } + else { + 0 + } + + $_.DeviceID + ' ' + $free + '/' + $size + 'GB free (' + $pct + '%)' + }) -join '; ' + } + else { + 'Unknown' + } + + $hotfixText = if ($latestHotfix) { + $date = if ($latestHotfix.InstalledOn) { + $latestHotfix.InstalledOn.ToString('yyyy-MM-dd') + } + else { + 'date unknown' + } + $latestHotfix.HotFixID + ' (' + $date + ')' + } + else { + 'Unavailable' + } + + $defenderText = 'Unavailable' + if (Get-Command Get-MpComputerStatus -ErrorAction SilentlyContinue) { + try { + $def = Get-MpComputerStatus -ErrorAction Stop + $rt = if ($def.RealTimeProtectionEnabled) { 'ON' } else { 'OFF' } + $sig = if ($def.AntivirusSignatureLastUpdated) { + $def.AntivirusSignatureLastUpdated.ToString('yyyy-MM-dd HH:mm') + } + else { + 'unknown' + } + $defenderText = 'Realtime ' + $rt + '; signatures ' + $sig + } + catch { + $defenderText = 'Unavailable' + } + } + + $biosText = $bios.SMBIOSBIOSVersion + if ([string]::IsNullOrWhiteSpace($biosText)) { + $biosText = $bios.Name + } + + Write-Both $writer 'WINDOWS MAINTENANCE SNAPSHOT' + Write-Both $writer ('Generated: ' + (Get-Date -Format 'yyyy-MM-dd HH:mm:ss')) + Write-Both $writer ('Computer: ' + $computerName + ' | ' + $system.Manufacturer + ' ' + $system.Model) + Write-Both $writer ('OS: ' + $os.Caption + ' | ' + $os.Version + ' build ' + $os.BuildNumber + ' | ' + $os.OSArchitecture) + Write-Both $writer ('BIOS: ' + $biosText) + Write-Both $writer ('CPU: ' + $cpu.Name + ' | ' + $cpu.NumberOfCores + 'C/' + $cpu.NumberOfLogicalProcessors + 'T') + Write-Both $writer ('RAM: ' + $ramFreeGB + 'GB free / ' + $ramTotalGB + 'GB total') + Write-Both $writer ('GPU: ' + $gpuText) + Write-Both $writer ('Storage: ' + $diskText) + Write-Both $writer ('DiskHealth: ' + (Get-DiskHealthSummary)) + Write-Both $writer ('Software: ' + $programs.Count + ' desktop programs; ' + (@(Get-AppxPackage -ErrorAction SilentlyContinue)).Count + ' AppX packages') + Write-Both $writer ('Startup: ' + $startupRegistry.Count + ' registry entries; ' + $startupCommands.Count + ' startup commands') + Write-Both $writer ('Services: ' + $autoServices.Count + ' automatic; ' + $stoppedAuto.Count + ' not running') + Write-Both $writer ('Devices: ' + $problemDevices.Count + ' reporting problems') + Write-Both $writer ('Update: ' + $hotfixText) + Write-Both $writer ('Defender: ' + $defenderText) + Write-Both $writer ('Uptime: ' + $uptime.Days + 'd ' + $uptime.Hours + 'h ' + $uptime.Minutes + 'm | Admin: ' + $isAdmin) + Write-Both $writer ('Report: ' + $reportPath) + + return + } + + # ---------------------------------------------------------------------- + # MID + FULL COMMON SECTIONS + # ---------------------------------------------------------------------- + Write-Both $writer 'WINDOWS SYSTEM / MAINTENANCE REPORT' + Write-Both $writer ('Mode: ' + $mode) + Write-Both $writer ('Generated: ' + (Get-Date -Format 'yyyy-MM-dd HH:mm:ss K')) + Write-Both $writer ('Computer: ' + $computerName) + Write-Both $writer ('User: ' + $env:USERNAME) + Write-Both $writer ('Administrator: ' + $isAdmin) + Write-Both $writer ('PowerShell: ' + $PSVersionTable.PSVersion) + Write-Both $writer ('Report: ' + $reportPath) + + if (-not $isAdmin) { + Write-Both $writer '' + Write-Both $writer 'NOTE: Script is not elevated. Admin-only diagnostics will be skipped.' + } Write-Section $writer 'OPERATING SYSTEM / COMPUTER / BIOS' { Get-CimInstance Win32_OperatingSystem | Select-Object Caption, Version, BuildNumber, OSArchitecture, InstallDate, LastBootUpTime, LocalDateTime, - @{N='TotalMemoryGB';E={[math]::Round($_.TotalVisibleMemorySize / 1MB, 2)}}, - @{N='FreeMemoryGB';E={[math]::Round($_.FreePhysicalMemory / 1MB, 2)}} | + @{Name='TotalMemoryGB';Expression={[math]::Round($_.TotalVisibleMemorySize / 1MB, 2)}}, + @{Name='FreeMemoryGB';Expression={[math]::Round($_.FreePhysicalMemory / 1MB, 2)}} | Format-List Get-CimInstance Win32_ComputerSystem | Select-Object Manufacturer, Model, SystemType, - @{N='TotalPhysicalMemoryGB';E={[math]::Round($_.TotalPhysicalMemory / 1GB, 2)}}, + @{Name='TotalPhysicalMemoryGB';Expression={[math]::Round($_.TotalPhysicalMemory / 1GB, 2)}}, Domain, PartOfDomain | Format-List @@ -197,18 +390,6 @@ try { Format-List } - Write-Section $writer 'UPTIME' { - $os = Get-CimInstance Win32_OperatingSystem - $uptime = (Get-Date) - $os.LastBootUpTime - - [PSCustomObject]@{ - LastBoot = $os.LastBootUpTime - Days = $uptime.Days - Hours = $uptime.Hours - Minutes = $uptime.Minutes - } | Format-List - } - Write-Section $writer 'CPU' { Get-CimInstance Win32_Processor | Select-Object Name, Manufacturer, NumberOfCores, @@ -220,7 +401,7 @@ try { Write-Section $writer 'MEMORY MODULES' { Get-CimInstance Win32_PhysicalMemory | Select-Object BankLabel, DeviceLocator, - @{N='CapacityGB';E={[math]::Round($_.Capacity / 1GB, 2)}}, + @{Name='CapacityGB';Expression={[math]::Round($_.Capacity / 1GB, 2)}}, Speed, ConfiguredClockSpeed, Manufacturer, PartNumber | Format-Table -AutoSize } @@ -233,63 +414,64 @@ try { Write-Section $writer 'GPU / DISPLAY ADAPTERS' { Get-CimInstance Win32_VideoController | - Select-Object Name, DriverVersion, - @{N='VRAM_GB';E={ - if ($_.AdapterRAM) { - [math]::Round($_.AdapterRAM / 1GB, 2) - } - else { - $null - } - }}, - VideoModeDescription | + Select-Object Name, DriverVersion, VideoModeDescription | Format-Table -AutoSize } - Write-Section $writer 'LOGICAL DISKS / FREE SPACE' { + Write-Section $writer 'STORAGE / FREE SPACE / HEALTH' { + 'Logical volumes:' Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3" | Select-Object DeviceID, VolumeName, FileSystem, - @{N='SizeGB';E={[math]::Round($_.Size / 1GB, 2)}}, - @{N='FreeGB';E={[math]::Round($_.FreeSpace / 1GB, 2)}}, - @{N='FreePercent';E={ + @{Name='SizeGB';Expression={[math]::Round($_.Size / 1GB, 2)}}, + @{Name='FreeGB';Expression={[math]::Round($_.FreeSpace / 1GB, 2)}}, + @{Name='FreePercent';Expression={ if ($_.Size) { [math]::Round(($_.FreeSpace / $_.Size) * 100, 1) } }} | Format-Table -AutoSize - } - Write-Section $writer 'PHYSICAL DISKS' { + '' + 'Physical disks:' Get-CimInstance Win32_DiskDrive | Select-Object Model, InterfaceType, MediaType, - @{N='SizeGB';E={[math]::Round($_.Size / 1GB, 2)}}, + @{Name='SizeGB';Expression={[math]::Round($_.Size / 1GB, 2)}}, FirmwareRevision, SerialNumber, Status | Format-Table -AutoSize - } - Write-Section $writer 'STORAGE HEALTH / RELIABILITY' { + '' + 'Storage health:' if (Get-Command Get-PhysicalDisk -ErrorAction SilentlyContinue) { - Get-PhysicalDisk | - Select-Object FriendlyName, MediaType, HealthStatus, - OperationalStatus, - @{N='SizeGB';E={[math]::Round($_.Size / 1GB, 2)}} | - Format-Table -AutoSize + try { + Get-PhysicalDisk -ErrorAction Stop | + Select-Object FriendlyName, MediaType, HealthStatus, + OperationalStatus, + @{Name='SizeGB';Expression={[math]::Round($_.Size / 1GB, 2)}} | + Format-Table -AutoSize - Get-PhysicalDisk | ForEach-Object { - "" - "Disk: $($_.FriendlyName)" - - try { - $_ | Get-StorageReliabilityCounter -ErrorAction Stop | - Select-Object Temperature, Wear, - ReadErrorsTotal, WriteErrorsTotal, - PowerOnHours | - Format-List + if ($isAdmin) { + Get-PhysicalDisk | ForEach-Object { + '' + 'Reliability: ' + $_.FriendlyName + try { + $_ | Get-StorageReliabilityCounter -ErrorAction Stop | + Select-Object Temperature, Wear, + ReadErrorsTotal, WriteErrorsTotal, + PowerOnHours | + Format-List + } + catch { + 'Reliability counters unavailable: ' + $_.Exception.Message + } + } } - catch { - 'Storage reliability counters unavailable.' + else { + 'Detailed reliability counters skipped: not elevated.' } } + catch { + 'Storage health unavailable: ' + $_.Exception.Message + } } else { 'Get-PhysicalDisk is unavailable on this system.' @@ -297,124 +479,53 @@ try { } Write-Section $writer 'INSTALLED PROGRAMS' { - $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 | + Get-InstalledPrograms | Format-Table -AutoSize } Write-Section $writer 'MICROSOFT STORE / APPX PACKAGES' { if (Get-Command Get-AppxPackage -ErrorAction SilentlyContinue) { - Get-AppxPackage | + Get-AppxPackage -ErrorAction SilentlyContinue | Select-Object Name, Version, Publisher, Architecture | Sort-Object Name | Format-Table -AutoSize } - } - - Write-Section $writer 'STARTUP PROGRAMS' { - Get-CimInstance Win32_StartupCommand | - Select-Object Name, Command, Location, User | - Sort-Object Name | - Format-Table -Wrap -AutoSize - } - - Write-Section $writer 'STARTUP REGISTRY LOCATIONS' { - $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) { - "" - "[$key]" - - if (Test-Path $key) { - $item = Get-ItemProperty $key - - $item.PSObject.Properties | - Where-Object {$_.Name -notlike 'PS*'} | - Select-Object Name, Value | - Format-Table -Wrap -AutoSize - } - else { - '(not present)' - } + else { + 'Get-AppxPackage is unavailable.' } } - Write-Section $writer 'STARTUP FOLDERS' { - $folders = @( - "$env:APPDATA\Microsoft\Windows\Start Menu\Programs\Startup", - "$env:ProgramData\Microsoft\Windows\Start Menu\Programs\Startup" - ) + Write-Section $writer 'STARTUP REGISTRY LOCATIONS' { + $entries = @(Get-StartupRegistryEntries) - foreach ($folder in $folders) { - "" - "Folder: $folder" - - if (Test-Path $folder) { - Get-ChildItem $folder -Force | - Select-Object Name, FullName, LastWriteTime | - Format-Table -AutoSize - } - else { - '(not present)' - } + if ($entries.Count -eq 0) { + '(no startup registry entries found)' + } + else { + $entries | + Sort-Object RegistryPath, Name | + Format-Table RegistryPath, Name, Value -Wrap -AutoSize } } Write-Section $writer 'AUTOMATIC SERVICES' { Get-CimInstance Win32_Service | - Where-Object {$_.StartMode -eq 'Auto'} | + Where-Object { $_.StartMode -eq 'Auto' } | Select-Object Name, DisplayName, State, StartMode, StartName | Sort-Object State, DisplayName | Format-Table -AutoSize } - Write-Section $writer 'AUTOMATIC SERVICES NOT RUNNING' { - Get-CimInstance Win32_Service | - Where-Object {$_.StartMode -eq 'Auto' -and $_.State -ne 'Running'} | - Select-Object Name, DisplayName, State, StartMode | - Format-Table -AutoSize - } - - Write-Section $writer 'DEVICES WITH PROBLEMS' { - if (Get-Command Get-PnpDevice -ErrorAction SilentlyContinue) { - Get-PnpDevice -PresentOnly -ErrorAction SilentlyContinue | - Where-Object {$_.Status -ne 'OK'} | - Select-Object Status, Class, FriendlyName, InstanceId | - Format-Table -Wrap -AutoSize - } - else { - Get-CimInstance Win32_PnPEntity | - Where-Object {$_.ConfigManagerErrorCode -ne 0} | - Select-Object Name, PNPClass, ConfigManagerErrorCode, DeviceID | - Format-Table -Wrap -AutoSize - } - } - Write-Section $writer 'SIGNED DRIVERS' { Get-CimInstance Win32_PnPSignedDriver | - Where-Object {$_.DeviceName} | + Where-Object { $_.DeviceName } | Select-Object DeviceName, Manufacturer, DriverVersion, DriverDate | Sort-Object DeviceName | Format-Table -AutoSize } Write-Section $writer 'WINDOWS UPDATES / HOTFIXES' { - Get-HotFix | + Get-HotFix -ErrorAction SilentlyContinue | Sort-Object InstalledOn -Descending | Select-Object HotFixID, Description, InstalledBy, InstalledOn | Format-Table -AutoSize @@ -422,144 +533,236 @@ try { Write-Section $writer 'WINDOWS DEFENDER STATUS' { if (Get-Command Get-MpComputerStatus -ErrorAction SilentlyContinue) { - Get-MpComputerStatus | - Select-Object AntivirusEnabled, AntispywareEnabled, - RealTimeProtectionEnabled, BehaviorMonitorEnabled, - IoavProtectionEnabled, NISEnabled, - AntivirusSignatureLastUpdated, - AntispywareSignatureLastUpdated, - QuickScanAge, FullScanAge | - Format-List + try { + Get-MpComputerStatus -ErrorAction Stop | + Select-Object AntivirusEnabled, AntispywareEnabled, + RealTimeProtectionEnabled, BehaviorMonitorEnabled, + IoavProtectionEnabled, NISEnabled, + AntivirusSignatureLastUpdated, + AntispywareSignatureLastUpdated, + QuickScanAge, FullScanAge | + Format-List + } + catch { + 'Defender status unavailable: ' + $_.Exception.Message + } } else { 'Microsoft Defender cmdlets unavailable.' } } - Write-Section $writer 'FIREWALL PROFILES' { - if (Get-Command Get-NetFirewallProfile -ErrorAction SilentlyContinue) { - Get-NetFirewallProfile | - Select-Object Name, Enabled, DefaultInboundAction, - DefaultOutboundAction | - Format-Table -AutoSize - } - } - - Write-Section $writer 'NETWORK ADAPTERS' { - if (Get-Command Get-NetAdapter -ErrorAction SilentlyContinue) { - Get-NetAdapter | - Select-Object Name, InterfaceDescription, Status, - LinkSpeed, MacAddress | - Format-Table -AutoSize - } - } - - Write-Section $writer 'IP CONFIGURATION' { - ipconfig /all - } - - Write-Section $writer 'DNS SERVERS' { - if (Get-Command Get-DnsClientServerAddress -ErrorAction SilentlyContinue) { - Get-DnsClientServerAddress | - Where-Object {$_.ServerAddresses.Count -gt 0} | - Select-Object InterfaceAlias, AddressFamily, - @{N='Servers';E={$_.ServerAddresses -join ', '}} | - Format-Table -AutoSize - } - } - - Write-Section $writer 'ACTIVE TCP LISTENERS' { - if (Get-Command Get-NetTCPConnection -ErrorAction SilentlyContinue) { - Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue | - Select-Object LocalAddress, LocalPort, OwningProcess | - Sort-Object LocalPort | - Format-Table -AutoSize - } - else { - netstat -ano - } - } - - Write-Section $writer 'POWER PLAN' { - powercfg /getactivescheme - } - - Write-Section $writer 'BATTERY' { - Get-CimInstance Win32_Battery -ErrorAction SilentlyContinue | - Select-Object Name, Status, EstimatedChargeRemaining, - EstimatedRunTime, BatteryStatus | - Format-List - } - Write-Section $writer 'NON-MICROSOFT SCHEDULED TASKS' { if (Get-Command Get-ScheduledTask -ErrorAction SilentlyContinue) { Get-ScheduledTask -ErrorAction SilentlyContinue | - Where-Object {$_.TaskPath -notlike '\Microsoft\*'} | + Where-Object { $_.TaskPath -notlike '\Microsoft\*' } | Select-Object TaskName, TaskPath, State | Sort-Object TaskPath, TaskName | Format-Table -AutoSize } } - Write-Section $writer 'TOP PROCESSES BY MEMORY' { - Get-Process | - Sort-Object WorkingSet64 -Descending | - Select-Object -First 30 ProcessName, Id, - @{N='MemoryMB';E={[math]::Round($_.WorkingSet64 / 1MB, 1)}}, - CPU | - Format-Table -AutoSize + # ---------------------------------------------------------------------- + # FULL-ONLY SECTIONS + # ---------------------------------------------------------------------- + if ($Full) { + Write-Section $writer 'UPTIME' { + $os = Get-CimInstance Win32_OperatingSystem + $uptime = (Get-Date) - $os.LastBootUpTime + + New-Object PSObject -Property @{ + LastBoot = $os.LastBootUpTime + Days = $uptime.Days + Hours = $uptime.Hours + Minutes = $uptime.Minutes + } | Format-List + } + + Write-Section $writer 'STARTUP PROGRAMS' { + Get-CimInstance Win32_StartupCommand | + Select-Object Name, Command, Location, User | + Sort-Object Name | + Format-Table -Wrap -AutoSize + } + + Write-Section $writer '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) { + '' + 'Folder: ' + $folder + + if (Test-Path $folder) { + Get-ChildItem $folder -Force -ErrorAction SilentlyContinue | + Select-Object Name, FullName, LastWriteTime | + Format-Table -AutoSize + } + else { + '(not present)' + } + } + } + + Write-Section $writer 'AUTOMATIC SERVICES NOT RUNNING' { + Get-CimInstance Win32_Service | + Where-Object { + $_.StartMode -eq 'Auto' -and $_.State -ne 'Running' + } | + Select-Object Name, DisplayName, State, StartMode | + Format-Table -AutoSize + } + + Write-Section $writer 'DEVICES WITH PROBLEMS' { + $devices = @(Get-ProblemDevices) + + if ($devices.Count -eq 0) { + '(no problem devices found)' + } + else { + $devices | + Select-Object Status, Class, FriendlyName, InstanceId, + Name, PNPClass, ConfigManagerErrorCode, DeviceID | + Format-Table -Wrap -AutoSize + } + } + + Write-Section $writer 'FIREWALL PROFILES' { + if (Get-Command Get-NetFirewallProfile -ErrorAction SilentlyContinue) { + Get-NetFirewallProfile -ErrorAction SilentlyContinue | + Select-Object Name, Enabled, DefaultInboundAction, + DefaultOutboundAction | + Format-Table -AutoSize + } + else { + 'Get-NetFirewallProfile is unavailable.' + } + } + + Write-Section $writer 'NETWORK ADAPTERS' { + if (Get-Command Get-NetAdapter -ErrorAction SilentlyContinue) { + Get-NetAdapter -ErrorAction SilentlyContinue | + Select-Object Name, InterfaceDescription, Status, + LinkSpeed, MacAddress | + Format-Table -AutoSize + } + } + + Write-Section $writer 'IP CONFIGURATION' { + ipconfig /all + } + + Write-Section $writer 'DNS SERVERS' { + if (Get-Command Get-DnsClientServerAddress -ErrorAction SilentlyContinue) { + Get-DnsClientServerAddress -ErrorAction SilentlyContinue | + Where-Object { $_.ServerAddresses.Count -gt 0 } | + Select-Object InterfaceAlias, AddressFamily, + @{Name='Servers';Expression={$_.ServerAddresses -join ', '}} | + Format-Table -AutoSize + } + } + + Write-Section $writer 'ACTIVE TCP LISTENERS' { + if (Get-Command Get-NetTCPConnection -ErrorAction SilentlyContinue) { + Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue | + Select-Object LocalAddress, LocalPort, OwningProcess | + Sort-Object LocalPort | + Format-Table -AutoSize + } + else { + netstat -ano + } + } + + Write-Section $writer 'POWER PLAN' { + powercfg /getactivescheme + } + + Write-Section $writer 'BATTERY' { + Get-CimInstance Win32_Battery -ErrorAction SilentlyContinue | + Select-Object Name, Status, EstimatedChargeRemaining, + EstimatedRunTime, BatteryStatus | + Format-List + } + + Write-Section $writer 'TOP PROCESSES BY MEMORY' { + Get-Process | + Sort-Object WorkingSet64 -Descending | + Select-Object -First 30 ProcessName, Id, + @{Name='MemoryMB';Expression={[math]::Round($_.WorkingSet64 / 1MB, 1)}}, + CPU | + Format-Table -AutoSize + } + + Write-Section $writer ('RECENT SYSTEM ERRORS - LAST ' + $EventLogDays + ' DAYS') { + $start = (Get-Date).AddDays(-$EventLogDays) + + Get-WinEvent -FilterHashtable @{ + LogName = 'System' + Level = 2 + StartTime = $start + } -ErrorAction SilentlyContinue | + Select-Object -First $MaxEventErrors TimeCreated, Id, + ProviderName, Message | + Format-List + } + + Write-Section $writer ('RECENT APPLICATION ERRORS - LAST ' + $EventLogDays + ' DAYS') { + $start = (Get-Date).AddDays(-$EventLogDays) + + Get-WinEvent -FilterHashtable @{ + LogName = 'Application' + Level = 2 + StartTime = $start + } -ErrorAction SilentlyContinue | + Select-Object -First $MaxEventErrors TimeCreated, Id, + ProviderName, Message | + Format-List + } + + Write-Section $writer 'WINDOWS COMPONENT STORE STATUS' { + if ($isAdmin) { + '[RUNNING] DISM.exe /Online /Cleanup-Image /CheckHealth' + DISM.exe /Online /Cleanup-Image /CheckHealth + } + else { + 'Skipped: DISM /CheckHealth requires an elevated session.' + } + } + + Write-Section $writer 'SYSTEM FILE CHECK - VERIFY ONLY' { + if ($isAdmin) { + '[RUNNING] sfc.exe /verifyonly' + sfc.exe /verifyonly + } + else { + 'Skipped: sfc /verifyonly requires an elevated session.' + } + } + + Write-Section $writer 'IMPORTANT DIRECTORIES' { + $programFilesX86 = [Environment]::GetEnvironmentVariable('ProgramFiles(x86)') + + New-Object PSObject -Property @{ + WindowsDirectory = $env:WINDIR + SystemDrive = $env:SystemDrive + ProgramFiles = $env:ProgramFiles + ProgramFilesX86 = $programFilesX86 + ProgramData = $env:ProgramData + UserProfile = $env:USERPROFILE + Temp = $env:TEMP + } | Format-List + } } - Write-Section $writer "RECENT SYSTEM ERRORS - LAST $EventLogDays DAYS" { - $start = (Get-Date).AddDays(-$EventLogDays) - - Get-WinEvent -FilterHashtable @{ - LogName = 'System' - Level = 2 - StartTime = $start - } -ErrorAction SilentlyContinue | - Select-Object -First $MaxEventErrors TimeCreated, Id, - ProviderName, Message | - Format-List - } - - Write-Section $writer "RECENT APPLICATION ERRORS - LAST $EventLogDays DAYS" { - $start = (Get-Date).AddDays(-$EventLogDays) - - Get-WinEvent -FilterHashtable @{ - LogName = 'Application' - Level = 2 - StartTime = $start - } -ErrorAction SilentlyContinue | - Select-Object -First $MaxEventErrors TimeCreated, Id, - ProviderName, Message | - Format-List - } - - Write-Section $writer 'WINDOWS COMPONENT STORE STATUS' { - DISM.exe /Online /Cleanup-Image /CheckHealth - } - - Write-Section $writer 'SYSTEM FILE CHECK - VERIFY ONLY' { - sfc.exe /verifyonly - } - - Write-Section $writer 'IMPORTANT DIRECTORIES' { - [PSCustomObject]@{ - WindowsDirectory = $env:WINDIR - SystemDrive = $env:SystemDrive - ProgramFiles = $env:ProgramFiles - ProgramFilesX86 = ${env:ProgramFiles(x86)} - ProgramData = $env:ProgramData - UserProfile = $env:USERPROFILE - Temp = $env:TEMP - } | Format-List - } + Write-Both $writer '' + Write-Both $writer ('Completed: ' + (Get-Date -Format 'yyyy-MM-dd HH:mm:ss K')) + Write-Both $writer ('Saved to: ' + $reportPath) } finally { - $writer.Dispose() + if ($writer) { + $writer.Dispose() + } } - -Write-Host -Write-Host 'Report completed.' -Write-Host "Saved to: $reportPath" \ No newline at end of file