Skip to content

Instantly share code, notes, and snippets.

@Timberfang
Last active June 29, 2024 01:38
Show Gist options
  • Save Timberfang/450bd174fdee9ced6fc076ec71831560 to your computer and use it in GitHub Desktop.
Save Timberfang/450bd174fdee9ced6fc076ec71831560 to your computer and use it in GitHub Desktop.
Add and remove variables from a user's PATH
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."
}
}
}
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