iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐕

PowerShell Script to Optimize Windows PATH Environment Variables

に公開

The Windows PATH environment variable often blows up, causing commands to go missing, so I created a script to remove duplicates and optimize it.

It safely and automatically performs duplicate removal, path normalization, invalid path deletion, and sorting into the appropriate scopes (System/User).

Probably.

Start-Process powershell -Verb runAs -ArgumentList "-NoProfile -ExecutionPolicy Bypass -Command `"iwr -useb https://raw.githubusercontent.com/nuitsjp/optimize-environment-variables/refs/heads/main/src/Optimize-EnvironmentVariable.ps1 | iex`""

If you run it like this:

User PATH (chars: before 600 -> after 763, delta +163)
  Keep:
    - %USERPROFILE%\.dotnet\tools
    - %USERPROFILE%\AppData\Roaming\npm
  Update:
    - %USERPROFILE%\AppData\Local\Programs\Python\Launcher
    - %USERPROFILE%\AppData\Local\Programs\Python\Python312

...

Apply optimized PATH changes? (Y/N):

You will be asked for confirmation like this. To play it safe, the script is designed to take a backup.

    Directory: D:\optimize-environment-variables\src

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a---          2025/12/30    17:26           1477 machine-20251230172620.bac
-a---          2025/12/30    17:26            601 user-20251230172620.bac

In the unlikely event that something goes wrong, you can restore it by running the following commands:

[Environment]::SetEnvironmentVariable("Path", (Get-Content -Raw "user-20251230172620.bac").Trim(), "User")
[Environment]::SetEnvironmentVariable("Path", (Get-Content -Raw "machine-20251230172620.bac").Trim(), "Machine")

That's all!

Discussion