Created
May 19, 2024 13:40
-
-
Save zbalkan/7f7232c70d0a085c8921a8ccaa9a444b to your computer and use it in GitHub Desktop.
This script checks the Machine and User level environment variable PATH, and remove entries if the path does not exist. Requires Administrator Privileges.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$environments = @([EnvironmentVariableTarget]::Machine, [EnvironmentVariableTarget]::User) | |
foreach ($e in $environments) | |
{ | |
$path = ([Environment]::GetEnvironmentVariable('Path', $e)).Split(';', [StringSplitOptions]::RemoveEmptyEntries) | |
$pathList = [System.Collections.Generic.List[string]]::new() | |
foreach ($p in $path) | |
{ | |
if(Test-Path -Path $p) | |
{ | |
$pathList.Add($p) | |
} | |
else | |
{ | |
Write-Output "Removing non-existent path '$p' from Env:Path" | |
} | |
} | |
if ($path.Count -eq $pathList.Count) | |
{ | |
Write-Output "Nothing to clean in $e" | |
} | |
else{ | |
$newPath = [System.String]::Join(';', $pathList) + ';' | |
[System.Environment]::SetEnvironmentVariable('Path', $newPath, $e) | |
} | |
} | |
Write-Output 'Path cleanup completed.' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment