How do I keep each PATH entry only once?
Is there a way to get rid of the duplicates without manual editing?
Preferably without installing third-party software?
If you don't mind using a PowerShell script then you can remove duplicates using the following script from the Microsoft Script Center:
Script to check for duplicate paths in PATH environment variable
Sometimes repeated installation of software can add duplicate entries into the PATH environment variable. Since environment variable has a there is a hard coded limit in the size of this variable, there are chances that you may it that limit over a period of time. This script checks the PATH environment variable and removes any duplicate path entries.
$RegKey = ([Microsoft.Win32.Registry]::LocalMachine).OpenSubKey("SYSTEM\CurrentControlSet\Control\Session Manager\Environment", $True) $PathValue = $RegKey.GetValue("Path", $Null, "DoNotExpandEnvironmentNames") Write-host "Original path :" + $PathValue $PathValues = $PathValue.Split(";", [System.StringSplitOptions]::RemoveEmptyEntries) $IsDuplicate = $False $NewValues = @() ForEach ($Value in $PathValues) { if ($NewValues -notcontains $Value) { $NewValues += $Value } else { $IsDuplicate = $True } } if ($IsDuplicate) { $NewValue = $NewValues -join ";" $RegKey.SetValue("Path", $NewValue, [Microsoft.Win32.RegistryValueKind]::ExpandString) Write-Host "Duplicate PATH entry found and new PATH built removing all duplicates. New Path :" + $NewValue } else { Write-Host "No Duplicate PATH entries found. The PATH will remain the same." } $RegKey.Close()
Source How to check for duplicate paths in PATH environment variable
You could do this with a python package called pathtub (I am the author of this package)
Installation
pip install pathtub
Usage
from pathtub import clean
# Default parameter values shown
clean(sort=True, remove_non_existent=True, remove_user_duplicates=True)
What does it do
-
Removes duplicates and empty entries (
;;
) from the "User PATH" and "System PATH" (trailing backslash neglected when comparing two folders). Editing "System PATH" needs that python is executed with Admin rights. - Removing from "User PATH" the entries that are in the "System PATH" (optional, enabled by default). Controlled with the
remove_user_duplicates
-parameter. - Sorts PATH(s) alphabetically (optional, enabled by default). Controlled with the
sort
parameter. - Removes folders from PATH(s) that do not exist on the filesystem (optional, enabled by default). Controlled with the
remove_non_existent
-parameter.
For more detailed description, please see the documentation in GitHub.