Posted On September 9, 2022

PowerShell: How To Append to Windows Environmental Paths Permanently

kimconnect 0 comments
blog.KimConnect.com >> Codes >> 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:\ProgramData\chocolatey\bin' # '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 *

Related Post

PowerShell: Fix Clustered Disk Errors

# fixClusterDiskErrors.ps1function selectClusterName{ param($domainName=$env:USERDNSDOMAIN) write-host "Now scanning $domainName for all available cluster names. This may…

Basic HTML and HTML5: Nest Many Elements within a Single div Element

<h2>CatPhotoApp</h2><main><p>Click here to view more <a href="#">cat photos</a>.</p><a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying…

Update Windows with Restricted Internet Access

This script is an extract of a longer version with the features of simultaneous executions…