Remove-DuplicatesFromPathVariables.ps1

<#PSScriptInfo
.VERSION 0.0.1
.GUID 559c7b37-91f7-4c75-9db2-a809d2460987
.AUTHOR asherto
.COMPANYNAME asheroto
.TAGS PowerShell Windows remove duplicate path variable variables
.PROJECTURI https://gist.github.com/asheroto/fa216475272e58837b06c4be61088530
.RELEASENOTES
[Version 0.1] - Initial Release
#>


<#
.SYNOPSIS
    This PowerShell script will check the system PATH variable and the user PATH variable for duplicates and then remove any duplicates found.
.DESCRIPTION
    This PowerShell script will check the system PATH variable and the user PATH variable for duplicates and then remove any duplicates found.
.EXAMPLE
    Remove-DuplicatesFromPathVariables.ps1
.NOTES
    Version : 0.0.1
    Created by : asheroto
.LINK
    Project Site: https://gist.github.com/asheroto/fa216475272e58837b06c4be61088530
#>


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 ✔️✔️✔️"