<# EzClean for Windows — storage cleaner (PowerShell port of install.sh). Run (nothing is installed — runs once, then exits): irm https://ezclean.xyz/install.ps1 | iex # interactive & ([scriptblock]::Create((irm https://ezclean.xyz/install.ps1))) scan --fast $env:EZCLEAN_DRYRUN='1'; irm https://ezclean.xyz/install.ps1 | iex # plan only Safety model (ported from the bash engine, with Windows substitutions; see docs/adr/0001): - Default disposition is the Recycle Bin (recoverable). --hard deletes permanently. - --dry-run prints the exact plan and touches nothing. - Every deletion passes Test-SafeToDelete: it must resolve strictly inside the user's home, must not be a protected top-level folder, and must not traverse a reparse point (junction/symlink). 'danger'-risk items are never auto-selected. #> Set-StrictMode -Version Latest $ErrorActionPreference = 'Stop' $script:AppName = 'EzClean' $script:Version = '1.0.0' $script:BuildRef = 'dev' # substituted at release time # ---------------------------------------------------------------------------- # Flags. Resolve from $args tokens (works with `& ([scriptblock]::Create(...)) scan`) # OR EZCLEAN_* env vars (the only way to pass flags through `irm | iex`). Mirrors # the bash `for arg in "$@"` loop. # ---------------------------------------------------------------------------- $script:Action = 'interactive' # 'interactive' | 'scan' $script:Mode = 'fast' # 'fast' | 'deep' $script:ModeWasSet = $false $script:HardDelete = $false $script:DryRun = $false $script:AiMode = $false # --ai/--smart: pre-tick safe-to-reclaim items (on-device rules) $script:ShowHelp = $false foreach ($a in @($args)) { switch -Regex ($a) { '^scan$' { $script:Action = 'scan' } '^--(deep|full)$' { $script:Mode = 'deep'; $script:ModeWasSet = $true } '^--fast$' { $script:Mode = 'fast'; $script:ModeWasSet = $true } '^--hard$' { $script:HardDelete = $true } '^--(ai|smart)$' { $script:AiMode = $true } '^--(dry-run|print-plan)$' { $script:DryRun = $true } '^(-h|--help|help)$' { $script:ShowHelp = $true } default { } } } # Env overrides (for irm|iex and for the test suite). if ($env:EZCLEAN_ACTION) { $script:Action = $env:EZCLEAN_ACTION } if ($env:EZCLEAN_MODE) { $script:Mode = $env:EZCLEAN_MODE; $script:ModeWasSet = $true } # Treat only meaningful values as "on" — EZCLEAN_HARD='0'/'false'/'no' means off. if ($env:EZCLEAN_HARD -and $env:EZCLEAN_HARD -notin '0','false','no') { $script:HardDelete = $true } if ($env:EZCLEAN_DRYRUN -and $env:EZCLEAN_DRYRUN -notin '0','false','no') { $script:DryRun = $true } if ($env:EZCLEAN_AI -and $env:EZCLEAN_AI -notin '0','false','no') { $script:AiMode = $true } # ---------------------------------------------------------------------------- # Home. Every destructive path is built from here, so refuse to run unless it is # a real, absolute, existing directory (mirrors the bash $HOME validation). # EZCLEAN_HOME overrides (test suite injects a sandbox home). # ---------------------------------------------------------------------------- $script:HomeDir = if ($env:EZCLEAN_HOME) { $env:EZCLEAN_HOME } elseif ($env:USERPROFILE) { $env:USERPROFILE } else { $HOME } function Test-ValidHome { if ([string]::IsNullOrWhiteSpace($script:HomeDir)) { return $false } if (-not [System.IO.Path]::IsPathRooted($script:HomeDir)) { return $false } if (-not (Test-Path -LiteralPath $script:HomeDir -PathType Container)) { return $false } # Refuse a drive root (C:) or filesystem root: a root home would make the # whole partition look "inside home". Require at least one segment below root. $h = ([System.IO.Path]::GetFullPath($script:HomeDir)).TrimEnd('\','/') if ($h -match '^[A-Za-z]:$') { return $false } if ([string]::IsNullOrEmpty([System.IO.Path]::GetDirectoryName($h))) { return $false } return $true } # ---------------------------------------------------------------------------- # Output helpers. # ---------------------------------------------------------------------------- function Write-Section($text) { Write-Host ''; Write-Host $text -ForegroundColor White; Write-Host ('-' * 60) } function Write-Info($text) { Write-Host "-> $text" -ForegroundColor DarkGray } function Write-Done($text) { Write-Host "[ok] $text" -ForegroundColor Green } function Write-Warn($text) { Write-Host "[!] $text" -ForegroundColor Yellow } function Format-Size([long]$bytes) { if ($bytes -ge 1GB) { return ('{0:N1} GB' -f ($bytes / 1GB)) } if ($bytes -ge 1MB) { return ('{0:N1} MB' -f ($bytes / 1MB)) } if ($bytes -ge 1KB) { return ('{0:N0} KB' -f ($bytes / 1KB)) } return "$bytes B" } # Logical size (sum of .Length). Informational — may exceed real reclaimable # bytes for sparse images (.vhdx/.qcow2) or hardlinked content; the bash engine # uses `du` (on-disk blocks). Not used for any safety decision. function Get-PathSizeBytes([string]$Path) { try { if (Test-Path -LiteralPath $Path -PathType Leaf) { return [long]((Get-Item -LiteralPath $Path -Force).Length) } # -Force to include hidden; SilentlyContinue so a locked subfolder never aborts. # Skip cloud-only placeholders (OneDrive Files-On-Demand: Offline | RecallOnOpen # | RecallOnDataAccess = 0x441000) — they occupy ~0 local bytes, so counting # their logical size as reclaimable would be wrong (and avoids any hydration). $sum = (Get-ChildItem -LiteralPath $Path -Recurse -Force -File -ErrorAction SilentlyContinue | Where-Object { -not ($_.Attributes -band 0x441000) } | Measure-Object -Property Length -Sum).Sum if ($null -eq $sum) { return [long]0 } return [long]$sum } catch { return [long]0 } } # ---------------------------------------------------------------------------- # Candidate model. # ---------------------------------------------------------------------------- $script:Candidates = [System.Collections.Generic.List[object]]::new() function Get-ProtectedDirs([string]$HomeReal) { # Top-level user folders that are never deletable (exact match; children are # fine, e.g. AppData\Local\Temp is allowed but AppData itself is not). Mirrors # the bash engine's protected set, with Windows substitutions: Library->AppData, # Movies->Videos, +OneDrive. `.config` is kept (git/gh/WSL store tokens there). return @('Desktop','Documents','Downloads','Pictures','Music','Videos', 'AppData','OneDrive','.ssh','.gnupg','.config') | ForEach-Object { Join-Path $HomeReal $_ } } function Add-Candidate([string]$Risk, [string]$Name, [string]$Path, [long]$Bytes) { if ($Risk -eq 'danger') { return } if (-not (Test-Path -LiteralPath $Path)) { return } $homeR = ([System.IO.Path]::GetFullPath($script:HomeDir)).TrimEnd('\','/') $real = ([System.IO.Path]::GetFullPath($Path)).TrimEnd('\','/') # Must be strictly inside home, and never a protected top-level folder. if ($real -ieq $homeR) { return } $sep = [System.IO.Path]::DirectorySeparatorChar if (-not $real.ToLowerInvariant().StartsWith(($homeR + $sep).ToLowerInvariant())) { return } foreach ($p in (Get-ProtectedDirs $homeR)) { if ($real -ieq ([System.IO.Path]::GetFullPath($p)).TrimEnd('\','/')) { return } } # Dedupe by resolved path. foreach ($c in $script:Candidates) { if ($c.Real -ieq $real) { return } } $script:Candidates.Add([pscustomobject]@{ Risk = $Risk; Name = $Name; Path = $Path; Real = $real; Bytes = $Bytes; Selected = $false }) } function Add-ScanPath([string]$Risk, [string]$Name, [string]$Path) { if (-not (Test-Path -LiteralPath $Path)) { return } # 'danger' rows are list-only and never become candidates, so don't recurse to # size them — that would walk OneDrive/Documents/Pictures (huge / cloud-backed). if ($Risk -eq 'danger') { Write-Host ("{0,-9}" -f $Risk) -ForegroundColor Red -NoNewline Write-Host (" {0,-30} {1,12} {2}" -f $Name, '(list only)', $Path) return } $b = Get-PathSizeBytes $Path if ($b -gt 0) { $color = switch ($Risk) { 'safe' {'Green'} 'review' {'Yellow'} default {'Gray'} } Write-Host ("{0,-9}" -f $Risk) -ForegroundColor $color -NoNewline Write-Host (" {0,-30} {1,12} {2}" -f $Name, (Format-Size $b), $Path) Add-Candidate $Risk $Name $Path $b } } # ---------------------------------------------------------------------------- # Windows rule pack. %LOCALAPPDATA%, %APPDATA%, %TEMP% resolved relative to the # (possibly sandboxed) home so the test suite can exercise it. On a real machine # these env vars already point under the user profile. # ---------------------------------------------------------------------------- function Get-WinDirs { $h = $script:HomeDir return @{ Local = if ($env:EZCLEAN_HOME) { Join-Path $h 'AppData\Local' } elseif ($env:LOCALAPPDATA) { $env:LOCALAPPDATA } else { Join-Path $h 'AppData\Local' } Roaming = if ($env:EZCLEAN_HOME) { Join-Path $h 'AppData\Roaming' } elseif ($env:APPDATA) { $env:APPDATA } else { Join-Path $h 'AppData\Roaming' } Temp = if ($env:EZCLEAN_HOME) { Join-Path $h 'AppData\Local\Temp' } elseif ($env:TEMP) { $env:TEMP } else { Join-Path $h 'AppData\Local\Temp' } Home = $h } } function Invoke-ScanCore { Write-Section 'SAFE / GENERATED DATA' Write-Info 'Checking known cache/temp/package-manager folders...' $d = Get-WinDirs Add-ScanPath safe 'Temp files' $d.Temp Add-ScanPath safe 'LocalAppData Temp' (Join-Path $d.Local 'Temp') Add-ScanPath safe 'Thumbnail cache' (Join-Path $d.Local 'Microsoft\Windows\Explorer') Add-ScanPath safe 'Chrome cache' (Join-Path $d.Local 'Google\Chrome\User Data\Default\Cache') Add-ScanPath safe 'Edge cache' (Join-Path $d.Local 'Microsoft\Edge\User Data\Default\Cache') Add-ScanPath safe 'Brave cache' (Join-Path $d.Local 'BraveSoftware\Brave-Browser\User Data\Default\Cache') Add-ScanPath safe 'Firefox cache' (Join-Path $d.Local 'Mozilla\Firefox\Profiles') Add-ScanPath safe 'npm cache' (Join-Path $d.Roaming 'npm-cache') Add-ScanPath safe 'pnpm store' (Join-Path $d.Local 'pnpm\store') Add-ScanPath safe 'Yarn cache' (Join-Path $d.Local 'Yarn\Cache') Add-ScanPath safe 'pip cache' (Join-Path $d.Local 'pip\Cache') Add-ScanPath safe 'NuGet cache' (Join-Path $d.Home '.nuget\packages') Add-ScanPath safe 'NuGet HTTP cache' (Join-Path $d.Local 'NuGet\v3-cache') Add-ScanPath safe 'Go build cache' (Join-Path $d.Local 'go-build') Add-ScanPath safe 'Go module cache' (Join-Path $d.Home 'go\pkg\mod\cache') Add-ScanPath safe 'Gradle cache' (Join-Path $d.Home '.gradle\caches') Add-ScanPath safe 'Gradle dists' (Join-Path $d.Home '.gradle\wrapper\dists') Add-ScanPath safe 'Cargo cache' (Join-Path $d.Home '.cargo\registry\cache') Add-ScanPath safe 'VS Code cache' (Join-Path $d.Roaming 'Code\Cache') Write-Done 'Safe/generated scan complete' } function Invoke-ScanReview { Write-Section 'REVIEW NEEDED' Write-Info 'Checking downloads, dev tools and app data...' $d = Get-WinDirs Add-ScanPath review 'Downloads' (Join-Path $d.Home 'Downloads') Add-ScanPath review 'Docker Desktop' (Join-Path $d.Local 'Docker') Add-ScanPath review 'Android SDK' (Join-Path $d.Local 'Android\Sdk') Add-ScanPath review 'Gradle (full)' (Join-Path $d.Home '.gradle') Add-ScanPath review 'Maven repo' (Join-Path $d.Home '.m2\repository') Add-ScanPath review '.NET folder' (Join-Path $d.Home '.dotnet') Add-ScanPath review 'Android AVD' (Join-Path $d.Home '.android\avd') Add-ScanPath review 'Slack data' (Join-Path $d.Roaming 'Slack') Add-ScanPath review 'Discord data' (Join-Path $d.Roaming 'discord') Add-ScanPath review 'Teams cache' (Join-Path $d.Roaming 'Microsoft\Teams') Write-Done 'Review scan complete' } function Invoke-ScanDanger { Write-Section 'DANGER ZONE / PERSONAL DATA - LIST ONLY' Write-Info 'Personal data. Never auto-cleaned, shown for awareness only.' $d = Get-WinDirs Add-ScanPath danger 'Documents' (Join-Path $d.Home 'Documents') Add-ScanPath danger 'Pictures' (Join-Path $d.Home 'Pictures') Add-ScanPath danger 'OneDrive' (Join-Path $d.Home 'OneDrive') Add-ScanPath danger 'Outlook data' (Join-Path $d.Local 'Microsoft\Outlook') Write-Done 'Danger-zone scan complete' } function Get-ScanRoots { $d = Get-WinDirs if ($script:Mode -eq 'fast') { # Common dev project roots (mirrors the bash engine) — only the ones that # exist, so we don't waste time on absent dirs. $names = 'Desktop','Documents','Downloads','Projects','Code','dev','git','src','Developer','source\repos' return $names | ForEach-Object { Join-Path $d.Home $_ } | Where-Object { Test-Path -LiteralPath $_ } } return @($d.Home) } function Invoke-ScanInstallers { Write-Section 'OLD INSTALLERS / ARCHIVES IN DOWNLOADS' $dl = Join-Path (Get-WinDirs).Home 'Downloads' if (-not (Test-Path -LiteralPath $dl)) { Write-Host 'No Downloads folder.'; return } $cut = (Get-Date).AddDays(-7) $ext = '.exe','.msi','.zip','.rar','.7z','.iso','.dmg','.pkg' $found = $false Get-ChildItem -LiteralPath $dl -Recurse -File -Force -ErrorAction SilentlyContinue | Where-Object { $ext -contains $_.Extension.ToLowerInvariant() -and $_.LastWriteTime -lt $cut } | ForEach-Object { $found = $true $b = [long]$_.Length Write-Host ('{0,12} {1}' -f (Format-Size $b), $_.FullName) Add-Candidate review 'Old installer' $_.FullName $b } if (-not $found) { Write-Host 'No old installer/archive files found.' } Write-Done 'Installer/archive scan complete' } function Invoke-ScanNodeModules { Write-Section 'NODE_MODULES FOLDERS' $found = $false foreach ($root in (Get-ScanRoots)) { if (-not (Test-Path -LiteralPath $root)) { continue } Write-Info "Scanning node_modules in $root" # Manual walk that PRUNES: a matched node_modules is recorded but not # descended into (so nested node_modules aren't double-counted), and we # never follow reparse points. Mirrors the bash `find ... -prune`. $stack = [System.Collections.Generic.Stack[string]]::new() $stack.Push($root) while ($stack.Count -gt 0) { $dir = $stack.Pop() $children = $null try { $children = Get-ChildItem -LiteralPath $dir -Directory -Force -ErrorAction Stop } catch { continue } foreach ($c in $children) { if ($c.Attributes -band [System.IO.FileAttributes]::ReparsePoint) { continue } if ($c.Name -eq 'node_modules') { $found = $true $b = Get-PathSizeBytes $c.FullName Write-Host ('{0,12} {1}' -f (Format-Size $b), $c.FullName) Add-Candidate safe 'node_modules' $c.FullName $b # prune — do not descend into a matched node_modules } else { $stack.Push($c.FullName) } } } } if (-not $found) { Write-Host 'No node_modules folders found.' } Write-Done 'node_modules scan complete' } function Invoke-ScanLargeFiles { Write-Section 'LARGE FILES (> 500 MB)' $found = $false $vmExt = '.vhd','.vhdx','.vmdk','.vdi','.qcow2','.iso' foreach ($root in (Get-ScanRoots)) { if (-not (Test-Path -LiteralPath $root)) { continue } Write-Info "Scanning large files in $root" Get-ChildItem -LiteralPath $root -Recurse -File -Force -ErrorAction SilentlyContinue | Where-Object { $_.Length -gt 500MB } | ForEach-Object { $found = $true $b = [long]$_.Length Write-Host ('{0,12} {1}' -f (Format-Size $b), $_.FullName) $name = if ($vmExt -contains $_.Extension.ToLowerInvariant()) { 'VM / disk image' } else { 'Large file' } Add-Candidate review $name $_.FullName $b } } if (-not $found) { Write-Host 'No files larger than 500 MB found.' } Write-Done 'Large-file scan complete' } # ---------------------------------------------------------------------------- # Safety: last line of defense before any delete. PURE (takes the home root) so # the test suite can exercise it with a sandbox home on any OS. # ---------------------------------------------------------------------------- function Test-ChainHasReparsePoint([string]$Real, [string]$HomeReal) { # Walk the candidate and every ancestor down to home. Fail CLOSED: any node we # cannot confirm (GetAttributes throws) is treated as unsafe — never skipped. $cur = $Real while ($true) { try { $attr = [System.IO.File]::GetAttributes($cur) if ($attr -band [System.IO.FileAttributes]::ReparsePoint) { return $true } } catch { return $true } # cannot confirm -> unsafe if ($cur -ieq $HomeReal) { break } $parent = [System.IO.Path]::GetDirectoryName($cur) if ([string]::IsNullOrEmpty($parent) -or $parent -eq $cur) { break } if ($parent.Length -lt $HomeReal.Length) { break } $cur = $parent } return $false } function Test-HasDescendantReparsePoint([string]$Path) { # True if the directory contains ANY reparse point (junction/symlink) at any # depth. Manual stack walk that does NOT descend into reparse points (so the # enumeration itself never follows a junction). Fail CLOSED on enumeration error. if (-not (Test-Path -LiteralPath $Path -PathType Container)) { return $false } $stack = [System.Collections.Generic.Stack[string]]::new() $stack.Push($Path) while ($stack.Count -gt 0) { $dir = $stack.Pop() $entries = $null # An unreadable subdir (ACL-denied/locked) is skipped, not treated as a # whole-candidate failure: a recursive delete run as this same user can't # traverse it either, so it's no escape — and refusing the whole tree for # one locked file would needlessly skip legitimate cache folders. try { $entries = Get-ChildItem -LiteralPath $dir -Force -ErrorAction Stop } catch { continue } foreach ($e in $entries) { try { if ($e.Attributes -band [System.IO.FileAttributes]::ReparsePoint) { return $true } if ($e.PSIsContainer) { $stack.Push($e.FullName) } } catch { return $true } # can't read this entry's attributes -> fail closed } } return $false } function Test-SafeToDelete([string]$Path, [string]$HomeReal) { if ([string]::IsNullOrWhiteSpace($Path)) { return $false } $homeR = ([System.IO.Path]::GetFullPath($HomeReal)).TrimEnd('\','/') # Home must not be a drive root (C:) or filesystem root — else everything below # it would look "inside home". Defense in depth on top of Test-ValidHome. if ($homeR -match '^[A-Za-z]:$') { return $false } if ([string]::IsNullOrEmpty([System.IO.Path]::GetDirectoryName($homeR))) { return $false } # NB: assignment-from-try is PS6+; on Windows PowerShell 5.1 it is a parse error. # Initialise then assign inside the try so this parses on PS 3.0+. $real = $null try { $real = ([System.IO.Path]::GetFullPath($Path)).TrimEnd('\','/') } catch { return $false } if ([string]::IsNullOrEmpty($real)) { return $false } # Drive root (C:) or filesystem root. if ($real -match '^[A-Za-z]:$') { return $false } if ([string]::IsNullOrEmpty([System.IO.Path]::GetDirectoryName($real))) { return $false } # Home itself. if ($real -ieq $homeR) { return $false } # Must exist. if (-not (Test-Path -LiteralPath $real)) { return $false } # Strictly inside home. $sep = [System.IO.Path]::DirectorySeparatorChar if (-not $real.ToLowerInvariant().StartsWith(($homeR + $sep).ToLowerInvariant())) { return $false } # No reparse point (junction/symlink) anywhere in the chain down to home... if (Test-ChainHasReparsePoint $real $homeR) { return $false } # ...nor any reparse point *inside* the tree: a recursive delete/recycle on # Windows PowerShell 5.1 follows junctions and would wipe their targets outside # home. Refuse such trees (fail closed; rare in cache folders). if ((Test-Path -LiteralPath $real -PathType Container) -and (Test-HasDescendantReparsePoint $real)) { return $false } # Protected top-level user folders (exact match; children are fine). foreach ($p in (Get-ProtectedDirs $homeR)) { if ($real -ieq ([System.IO.Path]::GetFullPath($p)).TrimEnd('\','/')) { return $false } } return $true } $script:RecycleApiReady = $false function Initialize-RecycleApi { # Microsoft.VisualBasic.FileIO.FileSystem is NOT available on PowerShell 7 # (.NET Core only ships Microsoft.VisualBasic.Core). Use the Win32 # SHFileOperation API via P/Invoke instead — it sends to the Recycle Bin on # BOTH Windows PowerShell 5.1 and PowerShell 7, on Windows only. if ($script:RecycleApiReady) { return $true } if ($env:OS -ne 'Windows_NT') { return $false } $sig = @' using System; using System.Runtime.InteropServices; public static class EzCleanRecycle { [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] struct SHFILEOPSTRUCT { public IntPtr hwnd; public uint wFunc; public string pFrom; public string pTo; public ushort fFlags; public int fAnyOperationsAborted; public IntPtr hNameMappings; public string lpszProgressTitle; } [DllImport("shell32.dll", CharSet=CharSet.Unicode)] static extern int SHFileOperation(ref SHFILEOPSTRUCT lpFileOp); const uint FO_DELETE = 0x0003; const ushort FOF_SILENT = 0x0004, FOF_NOCONFIRMATION = 0x0010, FOF_ALLOWUNDO = 0x0040, FOF_NOERRORUI = 0x0400; public static int Recycle(string path) { var op = new SHFILEOPSTRUCT(); op.wFunc = FO_DELETE; op.pFrom = path + "\0\0"; // double-null terminated op.fFlags = (ushort)(FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_SILENT | FOF_NOERRORUI); return SHFileOperation(ref op); } } '@ try { Add-Type -TypeDefinition $sig -ErrorAction Stop; $script:RecycleApiReady = $true; return $true } catch { return $false } } function Move-ToRecycleBin([string]$Path) { if (-not (Initialize-RecycleApi)) { throw 'Recycle Bin API unavailable (Windows only).' } $rc = [EzCleanRecycle]::Recycle($Path) if ($rc -ne 0) { throw "SHFileOperation failed (code $rc) for: $Path" } if (Test-Path -LiteralPath $Path) { throw "Path still present after recycle: $Path" } } $script:Failures = 0 function Invoke-Disposition([string]$Path) { if ($script:DryRun) { if ($script:HardDelete) { Write-Host ('would remove {0}' -f $Path) } else { Write-Host ('would recycle {0}' -f $Path) } return } if ($script:HardDelete) { Write-Host ("Removing {0} ... " -f $Path) -NoNewline try { Remove-Item -LiteralPath $Path -Recurse -Force; Write-Host 'done' -ForegroundColor Green } catch { $script:Failures++; Write-Host ("failed: {0}" -f $_.Exception.Message) -ForegroundColor Red } } else { Write-Host ("Recycle {0} ... " -f $Path) -NoNewline try { Move-ToRecycleBin $Path; Write-Host 'done' -ForegroundColor Green } catch { $script:Failures++; Write-Host ("failed: {0}" -f $_.Exception.Message) -ForegroundColor Red } } } # ---------------------------------------------------------------------------- # Selection + preview. # ---------------------------------------------------------------------------- # EzClean AI rule (mirrors the bash ai_should_select). All `safe` items are # regenerable. Among `review` items, only clearly-regenerable build/dependency # caches and old installers qualify — never personal data (downloads, chat/app # data, media, documents). Pure local string rule; no network, no model. function Test-AiShouldSelect([string]$Risk, [string]$Name) { if ($Risk -eq 'safe') { return $true } if ($Risk -eq 'review') { return ($Name -in @( 'Docker Desktop', 'Android SDK', 'Gradle (full)', 'Maven repo', '.NET folder', 'Android AVD', 'Old installer' )) } return $false } function Select-AiDefault { foreach ($c in $script:Candidates) { $c.Selected = (Test-AiShouldSelect $c.Risk $c.Name) } } # Default pre-selection (no TTY). 'safe' only — or, with --ai, the AI plan. function Select-SafeDefault { if ($script:AiMode) { Select-AiDefault; return } foreach ($c in $script:Candidates) { $c.Selected = ($c.Risk -eq 'safe') } } function Invoke-PreviewAndDelete { $selected = @($script:Candidates | Where-Object { $_.Selected }) Write-Section 'DELETE PREVIEW' if ($selected.Count -eq 0) { Write-Host 'No items selected. Nothing was deleted.'; return } $totalB = ($selected | Measure-Object -Property Bytes -Sum).Sum $i = 0 foreach ($c in $selected) { $i++ Write-Host ('[{0}] {1,-22} {2,10} {3}' -f $i, $c.Name, (Format-Size $c.Bytes), $c.Path) } Write-Host '' Write-Host ("Total selected: {0}" -f (Format-Size $totalB)) -ForegroundColor White if ($script:HardDelete) { Write-Warn 'Mode: permanent delete (--hard) — items will NOT be recoverable.' } else { Write-Info 'Mode: move to Recycle Bin (recoverable). Use --hard to delete permanently.' Write-Info 'Note: items larger than the Recycle Bin limit may be removed permanently by Windows.' } Write-Host '' if ($script:DryRun) { Write-Section 'DRY RUN — no files will be touched' foreach ($c in $selected) { # Validate AND dispose the same canonical path ($c.Real), not the raw string. if (Test-SafeToDelete $c.Real $script:HomeDir) { Invoke-Disposition $c.Real } else { Write-Host ('would SKIP {0} (unsafe: outside home, reparse point, or protected)' -f $c.Path) } } Write-Host '' Write-Done 'Dry run complete. Nothing was changed.' return } # Preflight the Recycle Bin API once so we fail with a clear message instead of # erroring per item (e.g. on a non-Windows host). if (-not $script:HardDelete -and -not (Initialize-RecycleApi)) { Write-Warn 'Recycle Bin is unavailable on this platform/runtime.' Write-Warn 'Re-run on Windows, or pass --hard to delete permanently (irreversible).' return } $verb = if ($script:HardDelete) { 'PERMANENTLY delete' } else { 'move to Recycle Bin' } if (-not (Read-YesNo ("{0} {1} item(s)?" -f $verb, $selected.Count))) { Write-Host 'Cancelled. No files were deleted.'; return } Write-Host '' $script:Failures = 0 foreach ($c in $selected) { # Validate AND dispose the same canonical path ($c.Real), not the raw string. if (-not (Test-SafeToDelete $c.Real $script:HomeDir)) { Write-Warn ("Skipped unsafe path (outside home, reparse point, or protected): {0}" -f $c.Path); continue } Invoke-Disposition $c.Real } Write-Host '' if ($script:Failures -gt 0) { Write-Warn ("{0} item(s) failed to delete (see messages above)." -f $script:Failures) } if ($script:HardDelete) { Write-Done 'Delete step complete' } else { Write-Done 'Moved to Recycle Bin. Empty it to reclaim the space.' } } # ---------------------------------------------------------------------------- # Interactive bits. Fall back to non-interactive when input is redirected # (e.g. running under a pipe / CI), like the bash /dev/tty guard. # ---------------------------------------------------------------------------- function Test-Interactive { try { return (-not [System.Console]::IsInputRedirected) } catch { return $false } } function Read-YesNo([string]$Prompt) { if (-not (Test-Interactive)) { return $false } while ($true) { Write-Host ("? {0} [y/N]: " -f $Prompt) -NoNewline -ForegroundColor Cyan $ans = Read-Host switch -Regex ($ans) { '^(y|yes)$' { return $true } '^(n|no|)$' { return $false } default { Write-Host 'Please answer yes or no.' } } } } function Select-ScanMode { if ($script:ModeWasSet) { return $true } if (-not (Test-Interactive)) { $script:Mode = 'fast'; return $true } $cursor = 0 while ($true) { Clear-Host Write-Host '' Write-Host " $script:AppName $script:Version" -ForegroundColor Cyan Write-Host ' Choose scan mode (Up/Down, Enter to confirm)' -ForegroundColor DarkGray Write-Host '' $fast = if ($cursor -eq 0) { '> [x] Fast scan - common cleanup spots (recommended)' } else { ' [ ] Fast scan - common cleanup spots (recommended)' } $deep = if ($cursor -eq 1) { '> [x] Full scan - deeper home sweep (slower)' } else { ' [ ] Full scan - deeper home sweep (slower)' } Write-Host $fast -ForegroundColor ($(if ($cursor -eq 0) { 'Green' } else { 'Gray' })) Write-Host $deep -ForegroundColor ($(if ($cursor -eq 1) { 'Green' } else { 'Gray' })) $key = [System.Console]::ReadKey($true) switch ($key.Key) { 'UpArrow' { $cursor = 0 } 'DownArrow' { $cursor = 1 } 'Enter' { $script:Mode = if ($cursor -eq 0) { 'fast' } else { 'deep' }; $script:ModeWasSet = $true; return $true } 'Q' { return $false } } } } function Select-DeleteItems { $count = $script:Candidates.Count if ($count -eq 0) { Write-Warn 'No cleanup candidates found.'; return $false } if (-not (Test-Interactive)) { Write-Warn 'No interactive console. Showing scan only.'; return $false } $cursor = 0 $window = 14 # With --ai, open with the safe-to-reclaim items pre-ticked and the cursor on # "Continue" so a single Enter confirms the AI plan. Still fully editable. if ($script:AiMode) { Select-AiDefault if (@($script:Candidates | Where-Object { $_.Selected }).Count -gt 0) { $cursor = $count } } while ($true) { Clear-Host Write-Host '' Write-Host 'Choose Items To Delete' -ForegroundColor White Write-Host ('-' * 60) Write-Host 'Up/Down to move, Space/Enter to tick. Tick "Continue" when done.' -ForegroundColor DarkGray if ($script:AiMode) { Write-Host '* EzClean AI pre-selected the safe-to-reclaim items. Untick anything to keep, then Continue.' -ForegroundColor Green } Write-Host '' $start = 0 if ($count -gt $window) { $start = $cursor - [int]($window / 2) if ($start -lt 0) { $start = 0 } if ($start -gt $count - $window) { $start = $count - $window } } $end = [Math]::Min($start + $window - 1, $count - 1) if ($start -gt 0) { Write-Host ' ...' -ForegroundColor DarkGray } for ($i = $start; $i -le $end; $i++) { $c = $script:Candidates[$i] $pointer = if ($i -eq $cursor) { '>' } else { ' ' } $check = if ($c.Selected) { 'x' } else { ' ' } Write-Host ('{0} [{1}] {2,-7} {3,-22} {4,10} {5}' -f $pointer, $check, $c.Risk, $c.Name, (Format-Size $c.Bytes), $c.Path) } if ($end -lt $count - 1) { Write-Host ' ...' -ForegroundColor DarkGray } $selCount = @($script:Candidates | Where-Object { $_.Selected }).Count $selBytes = ($script:Candidates | Where-Object { $_.Selected } | Measure-Object -Property Bytes -Sum).Sum if ($null -eq $selBytes) { $selBytes = 0 } Write-Host '' $contPointer = if ($cursor -eq $count) { '>' } else { ' ' } Write-Host ("{0} Continue to delete preview Selected: {1} | {2}" -f $contPointer, $selCount, (Format-Size $selBytes)) -ForegroundColor ($(if ($cursor -eq $count) { 'Green' } else { 'Cyan' })) $key = [System.Console]::ReadKey($true) switch ($key.Key) { 'UpArrow' { if ($cursor -gt 0) { $cursor-- } } 'DownArrow' { if ($cursor -lt $count) { $cursor++ } } { $_ -in 'Enter','Spacebar' } { if ($cursor -eq $count) { return $true } $script:Candidates[$cursor].Selected = -not $script:Candidates[$cursor].Selected } 'Q' { return $false } } } } # ---------------------------------------------------------------------------- # Orchestration. # ---------------------------------------------------------------------------- function Invoke-Scan { Write-Host '' Write-Host " $script:AppName $script:Version ($script:BuildRef)" -ForegroundColor Cyan Write-Host ' Clean space safely. Review findings, then choose.' -ForegroundColor DarkGray Write-Host ' Nothing is removed until you confirm.' -ForegroundColor DarkGray Write-Host '' Invoke-ScanCore Invoke-ScanReview Invoke-ScanDanger Invoke-ScanInstallers Invoke-ScanNodeModules Invoke-ScanLargeFiles Write-Host '' Write-Host 'Scan complete. No files were deleted during scan.' -ForegroundColor Green } function Invoke-DryRun { Invoke-Scan if ($script:Candidates.Count -eq 0) { Write-Warn 'No cleanup candidates found.'; return } Select-SafeDefault Invoke-PreviewAndDelete } function Invoke-Interactive { if (-not (Select-ScanMode)) { Write-Host 'Cancelled. No files were deleted.'; return } Invoke-Scan if (-not (Select-DeleteItems)) { Write-Host 'Cancelled. No files were deleted.'; return } Invoke-PreviewAndDelete } function Show-Help { @" $script:AppName $script:Version ($script:BuildRef) Usage (Windows PowerShell): irm https://ezclean.xyz/install.ps1 | iex # interactive & ([scriptblock]::Create((irm https://ezclean.xyz/install.ps1))) scan --fast `$env:EZCLEAN_DRYRUN='1'; irm https://ezclean.xyz/install.ps1 | iex # plan only Flags / tokens: scan Scan and report only. Never deletes. --fast Common cache/temp/dev folders (default). --deep,--full Adds large-file and full-home sweeps. Slower. --dry-run Print exactly what would be removed, then exit. No writes. --hard Permanently delete instead of moving to the Recycle Bin. --ai,--smart EzClean AI: open the menu with safe-to-reclaim items pre-ticked. (On-device, no network. You still review and confirm.) -h, --help Show this help. Env overrides (for `irm | iex`, which cannot take flags): EZCLEAN_ACTION=scan EZCLEAN_MODE=deep EZCLEAN_DRYRUN=1 EZCLEAN_HARD=1 EZCLEAN_AI=1 "@ | Write-Host } # ---------------------------------------------------------------------------- # Entry. Skipped entirely when dot-sourced for tests (EZCLEAN_NOMAIN=1). # ---------------------------------------------------------------------------- function Invoke-Main { Write-Host "$script:AppName $script:Version ($script:BuildRef)" -ForegroundColor DarkGray if ($script:ShowHelp) { Show-Help; return } if (-not (Test-ValidHome)) { Write-Warn ("`$HOME ('{0}') is not a valid absolute directory. Refusing to run." -f $script:HomeDir) return } if ($script:Action -eq 'scan') { Invoke-Scan; return } if ($script:DryRun) { Invoke-DryRun; return } Invoke-Interactive } if (-not $env:EZCLEAN_NOMAIN) { Invoke-Main }