Showing posts with label windows path. Show all posts
Showing posts with label windows path. Show all posts

Saturday, October 12, 2019

Powershell Script to append environment variable PATH in windows

Powershell Script to append environment variable PATH in windows

#Requires -RunAsAdministrator
<#
.Synopsis
   Script to append environment variable with new path
.DESCRIPTION
   This script will add a required path to path in windows environment variable
   Requires admin powershell prompt
   This script modifies registery, running without understanding might corrupt your windows installation
.EXAMPLE
   .\script.ps1 -PathToAdd "C:\program files\programname\bin"
#>
param(
[Parameter(Mandatory=$True,ValueFromPipeline=$True)]
[ValidateNotNullOrEmpty()]
[string[]]$PathToAdd
)
         
process{
    foreach($path in $PathToAdd)
    {
        try
        {
           Write-Warning "Path : $path"
           Test-Path (Resolve-Path $path -ErrorAction Stop) | Out-Null
  
            $currentPathStrings = (Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH).path.split(';')
            $currentPathStrings = $currentPathStrings | ? {$_.trim()}
            $pathToSave = $currentPathStrings + $path
            $pathStringToWrite = $pathToSave -join ';'
            Write-Warning "Writing below paths"
            Write-Output $pathStringToWrite
            try
            {
                Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH -Value $pathStringToWrite -ErrorAction Stop
            }
            catch
            {
                Write-Warning "Error writing to registry"
                Write-Output $_
            }
        }
        catch
        {
            Write-Warning "Above path you are trying to add could not be resolved, please check if it is a plain path and accessible from file explorer"
        }
    }
}