After a while working with a computer it’s not unusual for my %PATH% environment variable to become messy.
It tends to contain wrongly formatted paths, or paths that no longer exist from programs that have been uninstalled.
This was causing me problems when I ran a tool that relied on the path and was having trouble with it. Turns out this tool was pretty primitive and a touch too over-sensitive.
I had no idea which path it was choking on, and there are a lot of entries in my %PATH%, and many of them use environment variables, the I thought I’d quickly write a powershell script to fix what’s in there.
There are a couple of simple rules for %PATH%
- It’s a semi-colon separated list
- Don’t use quotes (“) in paths
- Spaces are permitted
- Environment variables of the form %NAME% are permitted.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
$paths = $env:Path -split ";" $validPaths = @() foreach ($path in $paths) { # Remove quotes form quoted paths if ($path -match ("^`".*`"$")) { $path = $Matches[1] } # Expand Environment Variables in path $expandPath = $path while ($expandPath -match "(%(.+?)%)") { $expandPath = $expandPath -replace $Matches[1], (Get-ChildItem "Env:\$($Matches[2])").Value } $validPaths += $path } $validPaths -join ";" |
The script simply checks each path isn’t surrounded by quotes, ensures the path exists (it has to resolve the environment variables first) and then returns a new string in the correct format for the %PATH% environment.
It returns the script to give you a chance to verify it yourself. But if you just want to update the %PATH% without that step, you can do this:
1 |
[Environment]::SetEnvironmentVariable("Path", (./Fix-Path.ps1), "Machine") |
Where “Fix-Path.ps1” is just a saved copy of the script above.