Last active
June 29, 2024 01:38
-
-
Save Timberfang/450bd174fdee9ced6fc076ec71831560 to your computer and use it in GitHub Desktop.
Add and remove variables from a user's PATH
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
function Add-ToPath { | |
[CmdletBinding()] | |
param ( | |
[Parameter(Mandatory)] | |
[string] | |
$Path | |
) | |
begin { | |
$UserPath = [Environment]::GetEnvironmentVariable('Path', 'User') | |
} | |
process { | |
if ( $UserPath.Contains($Path) ) { | |
Write-Error -Message "Error: $Path already exists in user's PATH." | |
} | |
elseif (Test-Path -Path $Path) { | |
# The method is required for environment changes to be permanent | |
[Environment]::SetEnvironmentVariable('Path', $UserPath + ";$Path", 'User') | |
Write-Verbose -Message "Added $Path to user's PATH." | |
} | |
else { | |
Write-Error -Message "Error: $Path does not exist." | |
} | |
} | |
} |
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
function Remove-FromPath { | |
[CmdletBinding()] | |
param ( | |
[Parameter(Mandatory)] | |
[string] | |
$Path | |
) | |
begin { | |
$UserPath = [Environment]::GetEnvironmentVariable('Path', 'User') | |
} | |
process { | |
if ( -not $UserPath.Contains($Path) ) { | |
Write-Error -Message "Error: $Path does not exist in user's PATH." | |
} | |
else { | |
# The method is required for environment changes to be permanent | |
[Environment]::SetEnvironmentVariable('Path', $UserPath.Replace($Path, ''), 'User') | |
Write-Verbose -Message "Removed $Path from user's PATH." | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment