How To Add or Remove a Path in Windows Environmental Paths

There are 2 functions to Add and Remove, at your convenience:

# addEnvironmentalPath.ps1

$pathToAdd='C:\Scripts'
$pathToRemove='C:\Scripts'

function addEnvironmentalPath($pathToAdd){
    $registryEnvironment='Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment'
    $pathToAdd=if($pathToAdd -match '\\$'){$pathToAdd -replace '.$'}else{$pathToAdd}
    try{
        $originalPaths=(Get-ItemProperty -Path $registryEnvironment -Name PATH).path
        $pathsArray=$originalPaths -split ';'|?{$_.trim() -ne ''}|%{if($_ -match '\\$'){$_ -replace '.$'}else{$_}}|Sort-Object -Unique
        if($pathToAdd -in $pathsArray){
            write-host "$pathToAdd is already included in the environmental paths: '$originalPaths'"
            return $true
        }else{
            $newPathsArray=$pathsArray+$pathToAdd
            $newPaths=$newPathsArray -join ';'
            Set-ItemProperty -Path $registryEnvironment -Name PATH -Value $newPaths
            $newRegistryEnvironment=(Get-ItemProperty -Path $registryEnvironment -Name PATH).Path
            write-host "Environmental paths have been changed:`r`nFrom: $originalPaths`r`nTo: $newPaths"
            return $true
        }
    }catch{
        write-warning $_
        return $false
    }
}

function removeEnvironmentalPath($pathToRemove){
    $registryEnvironment='Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment'
    $pathToRemove=if($pathToRemove -match '\\$'){$pathToRemove -replace '.$'}else{$pathToRemove}
    try{        
        $originalPaths=(Get-ItemProperty -Path $registryEnvironment -Name PATH).path
        $pathsArray=$originalPaths -split ';'|?{$_.trim() -ne ''}|%{if($_ -match '\\$'){$_ -replace '.$'}else{$_}}|Sort-Object -Unique
        if($pathToRemove -notin $pathsArray){
            write-host "$pathToRemove does not exist in the environmental paths: '$originalPaths'"
            return $true
        }else{
            $itemIndex=[array]::indexof($pathsArray,$pathToRemove)
            [System.Collections.ArrayList]$newPathsArrayList=$pathsArray
            $newPathsArrayList.RemoveAt($itemIndex)
            $newPaths=$newPathsArrayList -join ';'
            Set-ItemProperty -Path $registryEnvironment -Name PATH -Value $newPaths
            $newRegistryEnvironment=(Get-ItemProperty -Path $registryEnvironment -Name PATH).Path
            write-host "Environmental paths have been changed:`r`nFrom: $originalPaths`r`nTo: $newPaths"
            return $true            
        }
    }catch{
        write-warning $_
        return $false
    }
}

addEnvironmentalPath $pathToAdd
removeEnvironmentalPath $pathToRemove

Leave a Reply

Your email address will not be published. Required fields are marked *