Created
December 31, 2025 23:34
-
-
Save tallpeak/06cf9b8b3983aeebfbb9557f4308e812 to your computer and use it in GitHub Desktop.
remove-invalid-paths.ps1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # =============================================== | |
| # ACTION 1: REGISTRY BACKUP | |
| # =============================================== | |
| Write-Host "--- Starting Registry Backup ---" -ForegroundColor Yellow | |
| $BackupPath = "C:\RegBackups" | |
| if (-not (Test-Path -Path $BackupPath -PathType Container)) { | |
| Write-Host "Creating backup directory: $BackupPath" | |
| New-Item -Path $BackupPath -ItemType Directory | Out-Null | |
| } | |
| $Timestamp = Get-Date -Format "yyyyMMdd_HHmmss" | |
| $BackupFileName = "RegistryBackup_$Timestamp.reg" | |
| $FullBackupFile = Join-Path -Path $BackupPath -ChildPath $BackupFileName | |
| Write-Host "Starting registry export to: $FullBackupFile" | |
| # Use reg.exe to export the full registry (requires Admin rights) | |
| # The 2>&1 redirects stdout and stderr to the same stream for capture, and we check $LASTEXITCODE | |
| $RegExportResult = reg.exe EXPORT HKEY_USERS $FullBackupFile /y 2>&1 | |
| if ($LASTEXITCODE -eq 0) { | |
| Write-Host "✅ Registry backup completed successfully! Proceeding to PATH cleanup." -ForegroundColor Green | |
| Write-Host "File created: $FullBackupFile" | |
| } else { | |
| Write-Host "❌ FATAL ERROR: An error occurred during the registry backup." -ForegroundColor Red | |
| Write-Host "Error details (if available): $RegExportResult" -ForegroundColor Red | |
| # --- SAFETY EXIT --- | |
| Write-Host "Exiting script to prevent further actions without a backup." -ForegroundColor Red | |
| exit 1 | |
| # ------------------- | |
| } | |
| Write-Host "--------------------------------" -ForegroundColor Yellow | |
| # =============================================== | |
| # ACTION 2: PATH CLEANUP FUNCTION | |
| # =============================================== | |
| # ... (The Clean-EnvironmentPath function remains the same) | |
| function Clean-EnvironmentPath { | |
| param( | |
| [Parameter(Mandatory=$true)] | |
| [ValidateSet("User", "Machine")] | |
| [string]$Scope | |
| ) | |
| if ($Scope -eq "User") { | |
| $RegKeyPath = "HKCU:\Environment" | |
| } else { | |
| $RegKeyPath = "HKLM:\System\CurrentControlSet\Control\Session Manager\Environment" | |
| } | |
| Write-Host "`n--- Cleaning $($Scope) PATH Variable ---" -ForegroundColor Cyan | |
| try { | |
| $CurrentPath = (Get-ItemProperty -Path $RegKeyPath -Name Path -ErrorAction Stop).Path | |
| } catch { | |
| Write-Host "Could not retrieve the PATH variable from $RegKeyPath. Skipping." -ForegroundColor Red | |
| return | |
| } | |
| $PathEntries = $CurrentPath -split ';' | |
| $NewPathEntries = @() | |
| $InvalidEntries = @() | |
| foreach ($Entry in $PathEntries) { | |
| $Entry = $Entry.Trim() | |
| if ([string]::IsNullOrWhiteSpace($Entry)) { | |
| continue | |
| } | |
| if (Test-Path -Path $Entry -PathType Container) { | |
| $NewPathEntries += $Entry | |
| } else { | |
| $InvalidEntries += $Entry | |
| } | |
| } | |
| if ($InvalidEntries.Count -gt 0) { | |
| Write-Host "Found $($InvalidEntries.Count) non-existent directories to remove:" -ForegroundColor Yellow | |
| $InvalidEntries | ForEach-Object { Write-Host " - $_" } | |
| $NewPath = $NewPathEntries -join ';' | |
| try { | |
| # Note: Using -Type ExpandString is crucial for paths containing environment variables like %SystemRoot% | |
| Set-ItemProperty -Path $RegKeyPath -Name Path -Value $NewPath -Type ExpandString -Force -ErrorAction Stop | |
| Write-Host "`n✅ $($Scope) PATH successfully cleaned and updated in the Registry." -ForegroundColor Green | |
| $env:Path = $NewPath # Update current session | |
| [System.Environment]::SetEnvironmentVariable("PATH", $NewPath, $Scope) # Notify other apps | |
| } catch { | |
| Write-Host "`n❌ FAILED to write the new PATH to the Registry (Check permissions)." -ForegroundColor Red | |
| } | |
| } else { | |
| Write-Host "✨ No invalid paths found in the $($Scope) PATH variable. No changes made." -ForegroundColor Green | |
| } | |
| } | |
| # =============================================== | |
| # EXECUTION | |
| # =============================================== | |
| # 1. Clean the CURRENT USER's PATH | |
| Clean-EnvironmentPath -Scope "User" | |
| # 2. Clean the SYSTEM (Machine) PATH (Requires Admin rights) | |
| if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { | |
| Write-Host "`nSkipping Machine PATH cleanup: Script not run as Administrator." -ForegroundColor Red | |
| } else { | |
| Clean-EnvironmentPath -Scope "Machine" | |
| } | |
| Write-Host "`n--- Script Finished ---" -ForegroundColor Yellow |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment