PowerShell: View/Set Environment Variables
This page is a tutorial on using PowerShell to view or set environment variables.
For introduction on Microsoft Windows environment variable, see: Windows Environment Variables Tutorial .
Windows environment variable names are case-insensitive.
Environment variable are stored in Windows Registery. [Windows: Registry Tutorial] When PowerShell starts, it reads the Registry and export them into current session of PowerShell.
You can create, modify, or delete, environment variable in current session. These changes are temporary. Once you exit shell, the changes are gone.
You can create, modify, or delete, environment variable in the registry. These changes is permanent.
List Environment Variables
List environment variables:
Show env vars whose name contains “path”:
Show value of “path”:
$env:path -split ";"
Set Environment Variable in Current Session
Sets a env var named abc for current session:
$env:abc = "alice"
Get value of a env var:
Remove Environment Variable in Current Session
Deleting a env var from the current session:
# adding path to the path env var in current session $env:path = $env:path + ";C:\Program Files (x86)\ErgoEmacs\hunspell"
Permament Environment Variable
Permanent environment variable is stored in Windows Registry. When PowerShell launches, it reads the registry to get the env vars for the current session. However, it does not update the registry whenever you create or remove a env var using the
To manipulate env var in the registry for permanent use, use the .NET object like the following:
Show env var named “xyz” of the category “User”:
The possible values for the second argument in GetEnvironmentVariable are:
- Current session of PowerShell.
- Permanent, environment variable for current user. Stored in Registry.
- Permanent, environment variable for this machine. Stored in Registry. Require admin privilege.
Creates environment variable “xyz” of category “User”, and set the value to "3".
[Environment]::SetEnvironmentVariable("xyz", "3", "User")
[Environment]::SetEnvironmentVariable means calling the .NET object “Environment” and using its method “SetEnvironmentVariable”.
Example of adding a path to PATH:
[Environment]::SetEnvironmentVariable("PATH", $Env:Path + ";C:\Program Files (x86)\PHP", "User")
# removing a env var from registry [Environment]::SetEnvironmentVariable("xyz", $null, "User")
If you want PowerShell to update its env var session from the registry, exit PowerShell and start a new console.