<# .SYNOPSIS Clean-Windows.ps1 - Self-Service Windows Cleanup & Maintenance Utility Published by Cyber Highway LTD (https://www.cyberhighway.co.uk) Bedfordshire | 07378 510 974 | info@cyberhighway.co.uk .DESCRIPTION Scans common Windows temporary, cache and diagnostic folders to calculate recoverable disk space. By default, runs in safe PREVIEW (dry-run) mode and changes nothing on disk until you pass -Apply. Categories covered with -All: 1. User & System Temp folders (%TEMP%, C:\Windows\Temp, all user profiles) 2. Windows Prefetch cache (C:\Windows\Prefetch) 3. Windows Update download cache (SoftwareDistribution\Download) & Delivery Optimization 4. Windows Error Reporting (WER) archives and queues 5. Explorer thumbnail cache (thumbcache_*.db) 6. Windows Recycle Bin 7. DNS Resolver Cache (ipconfig /flushdns) .PARAMETER All Selects all cleanup categories. .PARAMETER Apply Executes the cleanup. Without -Apply, the script runs in Preview (dry-run) mode and only reports how much space would be freed. .PARAMETER TempAgeDays Only remove temporary files older than this many days (default: 0 = all unlocked temp files). .EXAMPLE Set-ExecutionPolicy -Scope Process Bypass .\Clean-Windows.ps1 -All # preview .\Clean-Windows.ps1 -All -Apply # do it. #> [CmdletBinding()] param( [switch]$All, [switch]$Apply, [switch]$Temp, [switch]$Prefetch, [switch]$WindowsUpdate, [switch]$ErrorReports, [switch]$ThumbnailCache, [switch]$RecycleBin, [switch]$DnsCache, [int]$TempAgeDays = 0 ) $ErrorActionPreference = 'Continue' # Default to -All if no specific category switch was provided if (-not ($All -or $Temp -or $Prefetch -or $WindowsUpdate -or $ErrorReports -or $ThumbnailCache -or $RecycleBin -or $DnsCache)) { $All = $true } $principal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent()) $isAdmin = $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) $modeLabel = if ($Apply) { 'APPLY MODE (LIVE CLEANUP)' } else { 'PREVIEW MODE (DRY RUN - NO FILES DELETED)' } $modeColor = if ($Apply) { 'Yellow' } else { 'Cyan' } Write-Host '' Write-Host '=====================================================================' -ForegroundColor DarkGreen Write-Host ' Cyber Highway LTD - Clean-Windows.ps1 Self-Service Utility' -ForegroundColor Green Write-Host " Mode: $modeLabel" -ForegroundColor $modeColor Write-Host '=====================================================================' -ForegroundColor DarkGreen if ($Apply -and -not $isAdmin) { Write-Warning 'Running -Apply without Administrator rights. System folders (C:\Windows\Temp, Windows Update cache) require an elevated PowerShell prompt.' } elseif (-not $isAdmin) { Write-Host '[Note] Running as standard user. Run PowerShell as Administrator for complete system-folder sizing.' -ForegroundColor DarkGray } $scriptRoot = if ($PSScriptRoot) { $PSScriptRoot } else { (Get-Location).Path } if ($Apply) { $logDir = Join-Path $scriptRoot 'Logs' New-Item -ItemType Directory -Path $logDir -Force -ErrorAction SilentlyContinue | Out-Null $stamp = Get-Date -Format 'yyyy-MM-dd_HHmmss' $logFile = Join-Path $logDir "Clean-Windows_$stamp.log" Start-Transcript -Path $logFile -Force -ErrorAction SilentlyContinue | Out-Null } function Get-DriveFreeGB([string]$DriveLetter = 'C') { try { $drv = Get-PSDrive -Name $DriveLetter -ErrorAction Stop return [math]::Round($drv.Free / 1GB, 2) } catch { return 0 } } $cutoff = if ($TempAgeDays -gt 0) { (Get-Date).AddDays(-$TempAgeDays) } else { [datetime]::MaxValue } $results = New-Object System.Collections.Generic.List[object] function Invoke-FolderCleanup { param( [string]$Category, [string]$Path, [string]$Filter = '*', [bool]$UseCutoff = $false ) if (-not (Test-Path -LiteralPath $Path)) { return } $items = Get-ChildItem -LiteralPath $Path -Filter $Filter -Recurse -Force -File -ErrorAction SilentlyContinue if ($UseCutoff -and $TempAgeDays -gt 0) { $items = $items | Where-Object { $_.LastWriteTime -lt $cutoff } } $countBefore = ($items | Measure-Object).Count $bytesBefore = [int64](($items | Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue).Sum) $mbBefore = [math]::Round($bytesBefore / 1MB, 2) if (-not $Apply) { $results.Add([pscustomobject]@{ Category = $Category Target = $Path Files = $countBefore EstimatedMB = $mbBefore FreedMB = 0.0 Status = 'Preview (Dry Run)' }) return } if ($UseCutoff -and $TempAgeDays -gt 0) { foreach ($f in $items) { Remove-Item -LiteralPath $f.FullName -Force -ErrorAction SilentlyContinue } } else { Get-ChildItem -LiteralPath $Path -Filter $Filter -Force -ErrorAction SilentlyContinue | ForEach-Object { Remove-Item -LiteralPath $_.FullName -Recurse -Force -ErrorAction SilentlyContinue } } $remaining = Get-ChildItem -LiteralPath $Path -Filter $Filter -Recurse -Force -File -ErrorAction SilentlyContinue if ($UseCutoff -and $TempAgeDays -gt 0) { $remaining = $remaining | Where-Object { $_.LastWriteTime -lt $cutoff } } $bytesAfter = [int64](($remaining | Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue).Sum) $freedMB = [math]::Max(0, [math]::Round(($bytesBefore - $bytesAfter) / 1MB, 2)) $results.Add([pscustomobject]@{ Category = $Category Target = $Path Files = $countBefore EstimatedMB = $mbBefore FreedMB = $freedMB Status = 'Cleaned' }) } $freeStartGB = Get-DriveFreeGB 'C' $startTime = Get-Date Write-Host ("`nHost: {0} | C: Free Space Before: {1:N2} GB`n" -f $env:COMPUTERNAME, $freeStartGB) -ForegroundColor Gray # 1. Temp Folders if ($All -or $Temp) { Write-Host '-> Checking temporary folders...' -ForegroundColor Cyan $tempTargets = @($env:TEMP, "$env:WINDIR\Temp", "$env:LOCALAPPDATA\Temp") if (Test-Path 'C:\Users') { Get-ChildItem 'C:\Users' -Directory -ErrorAction SilentlyContinue | ForEach-Object { $tempTargets += (Join-Path $_.FullName 'AppData\Local\Temp') } } $tempTargets | Where-Object { $_ } | Select-Object -Unique | ForEach-Object { Invoke-FolderCleanup -Category 'Temp Files' -Path $_ -UseCutoff $true } } # 2. Prefetch if ($All -or $Prefetch) { Write-Host '-> Checking Windows Prefetch...' -ForegroundColor Cyan Invoke-FolderCleanup -Category 'Prefetch' -Path "$env:WINDIR\Prefetch" } # 3. Windows Update Cache & Delivery Optimization if ($All -or $WindowsUpdate) { Write-Host '-> Checking Windows Update download cache...' -ForegroundColor Cyan $wuPath = "$env:WINDIR\SoftwareDistribution\Download" if ($Apply -and $isAdmin) { Stop-Service -Name wuauserv -Force -ErrorAction SilentlyContinue Stop-Service -Name bits -Force -ErrorAction SilentlyContinue } Invoke-FolderCleanup -Category 'Windows Update Cache' -Path $wuPath if ($Apply -and $isAdmin) { Start-Service -Name bits -ErrorAction SilentlyContinue Start-Service -Name wuauserv -ErrorAction SilentlyContinue try { Delete-DeliveryOptimizationCache -Force -ErrorAction Stop $results.Add([pscustomobject]@{ Category = 'Delivery Optimization' Target = 'Windows Delivery Optimization Cache' Files = 0 EstimatedMB = 0.0 FreedMB = 0.0 Status = 'Cleared' }) } catch { $results.Add([pscustomobject]@{ Category = 'Delivery Optimization' Target = 'Windows Delivery Optimization Cache' Files = 0 EstimatedMB = 0.0 FreedMB = 0.0 Status = 'Skipped / Empty' }) } } } # 4. Windows Error Reporting (WER) if ($All -or $ErrorReports) { Write-Host '-> Checking Windows Error Reporting archives...' -ForegroundColor Cyan Invoke-FolderCleanup -Category 'Error Reports (Archive)' -Path "$env:ProgramData\Microsoft\Windows\WER\ReportArchive" Invoke-FolderCleanup -Category 'Error Reports (Queue)' -Path "$env:ProgramData\Microsoft\Windows\WER\ReportQueue" } # 5. Explorer Thumbnail Cache if ($All -or $ThumbnailCache) { Write-Host '-> Checking Explorer thumbnail cache...' -ForegroundColor Cyan Invoke-FolderCleanup -Category 'Thumbnail Cache' -Path "$env:LOCALAPPDATA\Microsoft\Windows\Explorer" -Filter 'thumbcache_*.db' } # 6. Recycle Bin if ($All -or $RecycleBin) { Write-Host '-> Checking Recycle Bin...' -ForegroundColor Cyan $rbPath = 'C:\$Recycle.Bin' $rbFiles = Get-ChildItem -LiteralPath $rbPath -Recurse -Force -File -ErrorAction SilentlyContinue $rbCount = ($rbFiles | Measure-Object).Count $rbMB = [math]::Round(([int64](($rbFiles | Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue).Sum)) / 1MB, 2) if (-not $Apply) { $results.Add([pscustomobject]@{ Category = 'Recycle Bin' Target = 'All local drives ($Recycle.Bin)' Files = $rbCount EstimatedMB = $rbMB FreedMB = 0.0 Status = 'Preview (Dry Run)' }) } else { try { Clear-RecycleBin -Force -ErrorAction Stop $results.Add([pscustomobject]@{ Category = 'Recycle Bin' Target = 'All local drives ($Recycle.Bin)' Files = $rbCount EstimatedMB = $rbMB FreedMB = $rbMB Status = 'Emptied' }) } catch { $results.Add([pscustomobject]@{ Category = 'Recycle Bin' Target = 'All local drives ($Recycle.Bin)' Files = $rbCount EstimatedMB = $rbMB FreedMB = 0.0 Status = 'Already empty or skipped' }) } } } # 7. DNS Cache if ($All -or $DnsCache) { if (-not $Apply) { $results.Add([pscustomobject]@{ Category = 'DNS Cache' Target = 'Windows DNS Resolver' Files = 0 EstimatedMB = 0.0 FreedMB = 0.0 Status = 'Preview (Will flush with -Apply)' }) } else { Write-Host '-> Flushing DNS resolver cache...' -ForegroundColor Cyan ipconfig.exe /flushdns | Out-Null $results.Add([pscustomobject]@{ Category = 'DNS Cache' Target = 'Windows DNS Resolver' Files = 0 EstimatedMB = 0.0 FreedMB = 0.0 Status = 'Flushed' }) } } # Summary Table Write-Host '' Write-Host '=== Cleanup Summary ===' -ForegroundColor Green $results | Format-Table -Property Category, Target, Files, EstimatedMB, FreedMB, Status -AutoSize $totalEstMB = [math]::Round((($results | Measure-Object -Property EstimatedMB -Sum).Sum), 2) $totalFreedMB = [math]::Round((($results | Measure-Object -Property FreedMB -Sum).Sum), 2) $freeEndGB = Get-DriveFreeGB 'C' $elapsedSec = [math]::Round(((Get-Date) - $startTime).TotalSeconds, 1) if (-not $Apply) { Write-Host ("Preview complete in {0}s: ~{1:N2} MB ({2:N2} GB) can be reclaimed." -f $elapsedSec, $totalEstMB, ($totalEstMB / 1024)) -ForegroundColor Cyan Write-Host 'To perform the cleanup, run:' -ForegroundColor Yellow Write-Host ' .\Clean-Windows.ps1 -All -Apply' -ForegroundColor White } else { Write-Host ("Cleanup finished in {0}s." -f $elapsedSec) -ForegroundColor Green Write-Host ("Estimated space freed from folders : {0:N2} MB ({1:N2} GB)" -f $totalFreedMB, ($totalFreedMB / 1024)) -ForegroundColor Green Write-Host ("C: Free Space Before -> After : {0:N2} GB -> {1:N2} GB" -f $freeStartGB, $freeEndGB) -ForegroundColor Green if ($logFile) { Write-Host ("Transcript saved to : {0}" -f $logFile) -ForegroundColor Gray Stop-Transcript -ErrorAction SilentlyContinue | Out-Null } }