Skip to content

Instantly share code, notes, and snippets.

@i486
Forked from drazul/add-remove-windows-path.ps1
Created April 25, 2024 09:30
Show Gist options
  • Save i486/eb466fa6ba3f0456e14638b2dfb395bb to your computer and use it in GitHub Desktop.
Save i486/eb466fa6ba3f0456e14638b2dfb395bb to your computer and use it in GitHub Desktop.
Example to add and remove local-path to system-path-variable on Windows. Without the limitations of 1024 characters
#------------ Add path to system variable -------------------------------------
$path2add = ';C:\path;'
$systemPath = [Environment]::GetEnvironmentVariable('Path', 'machine');
If (!$systemPath.contains($path2add)) {
$systemPath += $path2add
$systemPath = $systemPath -join ';'
[Environment]::SetEnvironmentVariable('Path', $systemPath, 'Machine');
write-host "Added to path!"
write-host $systemPath
}
#------------ Delete path from system variable --------------------------------
$path2delete = 'C:\path;'
$systemPath = [Environment]::GetEnvironmentVariable('Path', 'machine');
$systemPath = $systemPath.replace($path2delete, '')
$systemPath = $systemPath -join ';'
[Environment]::SetEnvironmentVariable('Path', $systemPath, 'Machine');
write-host "Deleted from path!"
write-host $systemPath
#------------ Clean system variable -------------------------------------------
$systemPath = [Environment]::GetEnvironmentVariable('Path', 'machine');
while ($systemPath.contains(';;')) {
$systemPath = $systemPath.replace(';;', ';')
}
[Environment]::SetEnvironmentVariable('Path', $systemPath, 'Machine');
write-host "Cleaned path!"
write-host $systemPath
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment