Skip to content

Instantly share code, notes, and snippets.

@zbalkan
Created May 19, 2024 13:40
Show Gist options
  • Save zbalkan/7f7232c70d0a085c8921a8ccaa9a444b to your computer and use it in GitHub Desktop.
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.
$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