Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asheroto/fa216475272e58837b06c4be61088530 to your computer and use it in GitHub Desktop.
Save asheroto/fa216475272e58837b06c4be61088530 to your computer and use it in GitHub Desktop.
PowerShell script to remove duplicate entries from PATH environmental variables in Windows.

Remove Duplicate Entries from PATH Environmental Variables

This PowerShell script will check the system PATH variable and the user PATH variable for duplicates and then remove any duplicates found.

The script is NOT lazy - it actually checks each environmental variable separately, NOT simply $ENV:PATH.

Enjoy! 😊️️❤

Install Note

You can also install this script by typing...

Install-Script -Name Remove-DuplicatesFromPathVariables

As available on PowerShell Gallery.

example

Clear-Host;
# Begin
Write-Output "⏲️⏲️⏲️ Starting ⏲️⏲️⏲️"
Write-Output ("-" * 50)
Write-Output ""
# System PATH
Write-Output "🖥️ Checking System PATH 🖥️"
$TempMachinePath = [System.Environment]::GetEnvironmentVariable("Path", "Machine");
$Dupes = ($TempMachinePath.Split(";") | Group-Object | Where-Object { $_.Count -gt 1 }).Values;
if ($Dupes.Count -gt 0) { $Dupes | ForEach-Object { $TempMachinePath = $TempMachinePath.Replace("$_;", ""); $TempMachinePath += "$_;" }; [System.Environment]::SetEnvironmentVariable("Path", $TempMachinePath, "Machine") }
Write-Output @"
$("-" * 50)
Found duplicates
$("-" * 50)
$Dupes
$("-" * 50)
Removing duplicates, result...
$("-" * 50)
$TempMachinePath
"@;
# User PATH
Write-Output ""
Write-Output ("-" * 50)
Write-Output "🧑 Checking User PATH 🧑"
$TempUserPath = [System.Environment]::GetEnvironmentVariable("Path", "User");
$Dupes = ($TempUserPath.Split(";") | Group-Object | Where-Object { $_.Count -gt 1 }).Values;
if ($Dupes.Count -gt 0) { $Dupes | ForEach-Object { $TempUserPath = $TempUserPath.Replace("$_;", ""); $TempUserPath += "$_;" }; [System.Environment]::SetEnvironmentVariable("Path", $TempUserPath, "User") }
Write-Output @"
$("-" * 50)
Found duplicates
$("-" * 50)
$Dupes
$("-" * 50)
Removing duplicates, result...
$("-" * 50)
$TempUserPath
"@;
# Complete
Write-Output ""
Write-Output ("-" * 50)
Write-Output "✔️✔️✔️ Complete ✔️✔️✔️"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment