PowerShell: Set Path Environment Variable

By Xah Lee. Date: .

Add a Path to Environment Variable PATH, for Current User

Suppose you want to add c:/Users/xah/bin/ to it. Do:

$newPath = "C:/Users/xah/bin/";

$existingPaths = [environment]::GetEnvironmentVariable("path", "User");

[Environment]::SetEnvironmentVariable("path", $existingPaths + ";" + $newPath, "User")

restart PowerShell to see the new value.

Add a Path to Environment Variable PATH, for All Users

Suppose you want to add c:/Python39/ to $path for all users Do:

$newPath = "C:/Python39/";

$existingPaths = [environment]::GetEnvironmentVariable("path", "Machine");

[Environment]::SetEnvironmentVariable("path", $existingPaths + ";" + $newPath, "Machine")

restart PowerShell to see the new value.

Set Environment Variable PATH from a Array of Paths

This is a clean way to set the path.

# make sure no semicolon in any path
# make sure last string ends semicolon, not comma
$xpathsArray=
"C:\Users\xah\bin\ripgrep-13.0.0\",
"C:\Users\xah\bin\emacs-28.1\bin\",
"C:\Users\xah\go\bin",
"C:\Users\xah\.deno\bin",
"C:\Program Files\WindowsApps\Microsoft.PowerShell_7.2.5.0_x64__8wekyb3d8bbwe",
"C:\Users\xah\AppData\Local\Programs\Microsoft VS Code\bin",
"C:\Users\xah\AppData\Roaming\npm",
"C:\Users\xah\AppData\Local\Microsoft\WindowsApps";

$xpathsStr = $xpathsArray -join ";"

[Environment]::SetEnvironmentVariable("path", $xpathsStr, "User")

restart PowerShell to see the new value.

PowerShell: Environment Variable