Windows PATH 清理与去重

适用:Windows 10/11。脚本会把 HKCU\Environment\Path(用户 PATH)
与 HKLM\...\Environment\Path(系统 PATH)各自分别去重,备份到
.reg 文件后再写回注册表,任何时候双击备份即可回滚到改前的状态。


1. 流程概览

flowchart TD A[右键 PowerShell 以管理员身份运行] --> B[粘贴或运行脚本] B --> C[脚本自动导出当前 PATH 到 reg 文件] C --> D[分别读取系统 PATH 与用户 PATH] D --> E[逐项过滤损坏条目与占位符] E --> F[按标准化形式去重] F --> G[在屏幕上打印前后对比] G --> H[SetEnvironmentVariable 写回注册表] H --> I[广播环境变更消息] I --> J[重新打开终端窗口即可生效] H -.回滚.-> K[双击 backup 目录下的 reg 文件]

2. 完整脚本

脚本全 ASCII,可直接复制。下面是经过实战验证的版本:
已修复的两个坑(详见第六节):用字符遍历代替正则判断 CJK;
用 Start-Process -Verb RunAs 处理管理员提升。

#Requires -Version 5.1
# Optimize Windows PATH for the current user.
# Steps: backup registry -> dedupe each level -> write back HKCU + HKLM.
# Run with -Yes to skip the interactive confirmation.

[CmdletBinding()]
param([switch]$Yes)

$ErrorActionPreference = 'Stop'

# ---------- 0. setup ----------
$scriptDir = $PSScriptRoot
if ([string]::IsNullOrEmpty($scriptDir)) { $scriptDir = (Get-Location).Path }
$backupDir = Join-Path $scriptDir 'backup'
if (-not (Test-Path $backupDir)) { New-Item -ItemType Directory -Path $backupDir | Out-Null }
$stamp = (Get-Date).ToString('yyyyMMdd-HHmmss')

# ---------- 1. elevate to admin when needed (HKLM write requires it) ----------
$principal = New-Object Security.Principal.WindowsPrincipal(
    [Security.Principal.WindowsIdentity]::GetCurrent())
$isAdmin = $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)

if (-not $isAdmin) {
    Write-Host '[INFO] Re-launching as administrator for HKLM write access...'
    $argList = @('-NoProfile','-ExecutionPolicy','Bypass','-File', "`"$PSCommandPath`"")
    if ($Yes) { $argList += '-Yes' }
    try {
        $proc = Start-Process -FilePath 'powershell.exe' `
                              -ArgumentList $argList `
                              -Verb RunAs `
                              -WindowStyle Hidden `
                              -Wait `
                              -PassThru
        if ($proc.ExitCode -ne 0) {
            Write-Host "[ERROR] Elevated PowerShell exited with code $($proc.ExitCode)."
            exit $proc.ExitCode
        }
    } catch {
        Write-Host '[ERROR] UAC elevation failed. Please right-click this .ps1 file and choose "Run as administrator".'
        exit 1
    }
    # The elevated run already wrote everything; just exit.
    exit 0
}

# ---------- 2. backup registry to .reg files ----------
Write-Host ''
Write-Host '[STEP 1] Exporting registry .reg backups...'
$userBackup = Join-Path $backupDir "user-env-$stamp.reg"
$sysBackup  = Join-Path $backupDir "system-env-$stamp.reg"
reg.exe export 'HKCU\Environment' $userBackup /y | Out-Null
reg.exe export 'HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' $sysBackup /y | Out-Null
Write-Host "        User   -> $userBackup"
Write-Host "        System -> $sysBackup"

# ---------- 3. read current PATH ----------
$sysPath = [Environment]::GetEnvironmentVariable('Path','Machine')
$usrPath = [Environment]::GetEnvironmentVariable('Path','User')
if (-not $sysPath) { $sysPath = '' }
if (-not $usrPath) { $usrPath = '' }

Write-Host ''
Write-Host '[STEP 2] Current PATH:'
Write-Host "        System  ->  $($sysPath.Length) chars"
Write-Host "        User    ->  $($usrPath.Length) chars"

# ---------- 4. clean helper ----------
function Has-CJK {
    param([string]$s)
    if ([string]::IsNullOrEmpty($s)) { return $false }
    foreach ($ch in $s.ToCharArray()) {
        $cp = [int][char]$ch
        if ($cp -ge 0x4E00 -and $cp -le 0x9FFF) { return $true }
    }
    return $false
}

function Clean-Path {
    param([string]$Path)
    if ([string]::IsNullOrWhiteSpace($Path)) { return @() }

    $items = $Path -split ';' | ForEach-Object { $_.Trim() } | Where-Object { $_ -ne '' }

    $filtered = @()
    foreach ($item in $items) {
        $bad = $false

        # CJK chars => placeholder text unless it's the known legit Chinese path
        if (Has-CJK $item) {
            if (-not ($item -like 'D:\SoftwareTypes\*')) { $bad = $true }
        }

        # Drive root alone (C:\, C:/, C:) is never a useful PATH entry
        if ($item.Length -le 3 -and $item.Length -ge 2 -and $item[1] -eq ':' -and
            ($item.Length -eq 2 -or ($item.Length -ge 3 -and $item[2] -in @('\','/')))) {
            $bad = $true
        }

        # 8.3-style truncation (e.g. ends with Administra)
        if ($item -match 'Administra(\\|/|$)') { $bad = $true }

        # Must look like a Windows drive path or %VAR%
        if (-not ($item -match '^[A-Za-z]:' -or $item -match '^%')) { $bad = $true }

        if (-not $bad) { $filtered += $item }
    }

    # Dedup by normalized form (lower-case, / -> \, trim trailing \)
    $seen = @{}
    $result = @()
    foreach ($item in $filtered) {
        $norm = $item.Replace('/','\').ToLower()
        while ($norm.Length -gt 3 -and $norm.EndsWith('\')) {
            $norm = $norm.Substring(0, $norm.Length - 1)
        }
        if (-not $seen.ContainsKey($norm)) {
            $seen[$norm] = $true
            if ($item.Length -gt 3 -and $item.EndsWith('\')) {
                $result += $item.Substring(0, $item.Length - 1)
            } else {
                $result += $item
            }
        }
    }
    return ,$result
}

$cleanSysItems = Clean-Path -Path $sysPath
$cleanUsrItems = Clean-Path -Path $usrPath
$cleanSysPath = $cleanSysItems -join ';'
$cleanUsrPath = $cleanUsrItems -join ';'

# ---------- 5. diff report ----------
Write-Host ''
Write-Host '[STEP 3] Cleaned PATH:'
Write-Host "        System  ->  $($cleanSysItems.Count) items, $($cleanSysPath.Length) chars (was $(($sysPath -split ';').Count))"
Write-Host "        User    ->  $($cleanUsrItems.Count) items, $($cleanUsrPath.Length) chars (was $(($usrPath -split ';').Count))"
Write-Host ''
Write-Host '---- System PATH (final) ----'
Write-Host $cleanSysPath
Write-Host ''
Write-Host '---- User PATH (final) ----'
Write-Host $cleanUsrPath
Write-Host ''

# ---------- 6. confirm ----------
if (-not $Yes) {
    $ans = Read-Host 'Write to HKCU + HKLM now? (Y/n)'
    if ($ans -ne '' -and $ans -notmatch '^[Yy]') {
        Write-Host '[INFO] Cancelled. Registry NOT modified. Backups left at:'
        Write-Host "        $backupDir"
        exit 0
    }
}

# ---------- 7. apply ----------
[Environment]::SetEnvironmentVariable('Path', $cleanUsrPath, 'User')
[Environment]::SetEnvironmentVariable('Path', $cleanSysPath, 'Machine')

# Broadcast WM_SETTINGCHANGE so apps refresh their cached env.
Add-Type -Namespace W -Name N -MemberDefinition @'
[DllImport("user32.dll", SetLastError=true)]
public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint Msg, IntPtr wParam, string lParam, uint flags, uint timeout, out IntPtr result);
'@ | Out-Null
$HWND = [IntPtr]0xffff
$WM   = 0x001A
$result = [IntPtr]::Zero
[W.N]::SendMessageTimeout($HWND, $WM, [IntPtr]::Zero, 'Environment', 0, 1000, [ref]$result) | Out-Null

Write-Host '[OK] Registry updated. Reopen CMD/PowerShell to pick up the new PATH.'
Write-Host ''
Write-Host 'Rollback: double-click either .reg to restore.'
Get-ChildItem $backupDir -Filter '*.reg' | ForEach-Object { Write-Host "  $($_.FullName)" }

3. 使用方法

一次性使用(推荐先看效果)

  1. 在桌面或工作目录新建一个空文件夹,比如 D:\Tools\path-cleaner。

  2. 在该目录里新建文件 optimize-path.ps1,把上面的完整脚本粘贴进去保存。

  3. 在该文件夹空白处按住 Shift 右键,选 "在此处打开 PowerShell 窗口"
    (或 "在此处打开终端" / "在 Windows 终端中打开" )。

  4. 第一次跑,先不带 -Yes 看 diff 后再确认:

    powershell -NoProfile -ExecutionPolicy Bypass -File .\optimize-path.ps1
    
  5. 如果当前 PowerShell 不是管理员,脚本会自动弹出 UAC,点 "是" 即可继续。

  6. 看到 [STEP 3] 输出后,按回车确认,注册表就被改写。

  7. 关闭旧终端,新开一个 CMD/PowerShell,跑 echo %PATH% 即看到新值。

仅改用户级 PATH

如果不需要碰系统级,直接注释掉脚本"七、应用"那两行的第二行:

# [Environment]::SetEnvironmentVariable('Path', $cleanSysPath, 'Machine')

或者改用本机已有账号的方式,只要把管理员检测和 UAC 提升那段也注释掉即可。

跑过以后再跑一次

幂等。脚本的清理逻辑和去重逻辑在第二次运行时,会得到稳定的结果,不会再删除东西,也不会再产生新备份——但每次跑都会因为时间戳 yyyyMMdd-HHmmss 生成新的 .reg 文件(相当于又备份了一遍)。需要的话,定期清空 backup/ 目录即可。


4. 回滚办法

脚本同目录下会有 backup/ 文件夹,放着当次运行前的注册表快照:

backup\
├── system-env-20261013-223452.reg
└── user-env-20261013-223452.reg

双击 .reg 文件 → 选 "是" 即恢复。两次回滚的注册表会合并而非覆盖(因为 .reg 文件本质上是追加的键值导入),所以可以放心多次回滚。

要彻底还原到更早的状态,只能靠 Windows 自带的"系统还原点",或者重装。


5. 验证 PATH 是否生效

where python
where node
where java
where mvn
where git
where dotnet
where code

任一命令回显 "信息:找不到给定路径上的文件" 或 "不是内部或外部命令",
说明该工具不在新 PATH 中,需要重新安装或手动把它的 bin 目录加进去。

更稳妥的验证:

for %A in (python.exe node.exe java.exe mvn.cmd git.exe dotnet.exe code.exe) do @where %A

posted @ 2026-10-13 22:48  RK5123153  阅读(10)  评论(0)    收藏  举报