PowerShell: How To Append to Windows Environmental Paths Permanently

Often, when we install applications such as Python, its bin directory may not automatically be added to the OS environmental paths. Most of us would use the command $env:path+=”;$appendPath” to work around this issue; however, such command only works for that single user or session.

How do we make a permanent change to the System Environmental paths? Here’s a function for that.

*** WARNING: this is only for educational purposes. Please DO NOT apply this to PRODUCTION systems without knowing what you’re doing as misuse can lead to system failures! Please consult a professional. Caveat Emptor! ***

$appendPath='C:\Python38\Scripts'

function appendEnvironmentPaths($appendPath){
    $appendPath=if($appendPath -match '\\$'){$appendPath.Substring(0,$appendPath.Length-1)}else{$appendPath}
    $regEnvironmentPaths='Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment'
    $regKeyname='PATH'
    $systemPaths=(Get-ItemProperty -Path $regEnvironmentPaths -Name $regKeyname)."$regKeyname"
    $systemPathsArray=$systemPaths -split ';'
    $pathExists=.{
        $systemPathsArray|%{
            $path=if($_ -match '\\$'){$_.Substring(0,$_.Length-1)}else{$_}
            if($path -eq $appendPath){
                return $true
            }
        }
    }
    if(!$pathExists){
        $systemPaths+=";$appendPath"
        Set-Itemproperty -path $regEnvironmentPaths -Name $regKeyname -value $systemPaths
        write-host "$appendPath has been appended:`r`n$systemPaths"
$env:Path=[System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User")
    }else{
        write-host "$appendPath already exists in System Paths:`r`n$systemPaths"
    }
}

appendEnvironmentPaths $appendPath

Leave a Reply

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