DOS - A historical answer
For older systems, this is the way it was done and if you're working in in some flavor of Dos this is the easiest answer:
To print each entry of Windows PATH variable on a new line, execute:
C:\> echo %PATH:;=&echo.%
Set Windows PATH variable for the current session:
C:\> set PATH=%PATH%;C:\path\to\directory\
Set Windows PATH Permanently
Run as Administrator: The setx command is only available starting from Windows 7 and requires elevated command prompt.
Permanently add a directory to the user PATH variable:
C:\> setx path "%PATH%;C:\path\to\directory\"
Permanently add a directory to the system PATH variable (for all users):
C:\> setx /M path "%PATH%;C:\path\to\directory\"
PowerShell - To avoid problems on modern systems
On modern Windows there are more modern tools you can use to avoid some pitfalls that come with modern implementations of how the %PATH% variable is used.
What used to be user settings vs. system settings is now referred to as user vs machine settings. They are the same. User settings can be modified by anyone and only affects their own environment. Modification of Machine level settings require administrator privileges because they apply to all users.
To print each entry of Windows PATH variable on a new line, execute:
[Environment]::GetEnvironmentVariable("PATH", "User").Split(";")
[Environment]::GetEnvironmentVariable("PATH", "Machine").Split(";")
Set Windows PATH avoiding the pitfalls of setx method
The two main things we want to avoid are the character limit of 1024 and duplicate entries. Using the modern SetEnvironmentVariable
will avoid the 1024 character limit so we could do a simple thing:
function Add-Path-User($newPath) {
$Path = [Environment]::GetEnvironmentVariable("PATH", "User") + [IO.Path]::PathSeparator + $newPath
[Environment]::SetEnvironmentVariable( "Path", $Path, "User" )
}
function Add-Path-Machine($newPath) {
$Path = [Environment]::GetEnvironmentVariable("PATH", "Machine") + [IO.Path]::PathSeparator + $newPath
[Environment]::SetEnvironmentVariable( "Path", $Path, "Machine" )
}
But if you want to avoid duplicates you would need something more involved:
Function Set-PathVariable {
param (
[string]$AddPath,
[ValidateSet('Process', 'User', 'Machine')]
[string]$Scope = 'Process'
)
$regexPaths = @()
if ($PSBoundParameters.Keys -contains 'AddPath') {
$regexPaths += [regex]::Escape($AddPath)
}
$arrPath = [System.Environment]::GetEnvironmentVariable('PATH', $Scope).Split([IO.Path]::PathSeparator)
foreach ($path in $regexPaths) {
$arrPath = $arrPath | Where-Object { $_ -notMatch "^$path\\?$" }
}
$value = ($arrPath + $addPath).Join([IO.Path]::PathSeparator)
[System.Environment]::SetEnvironmentVariable('PATH', $value, $Scope)
}