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 NOT CASE SENSITIVE
Environment Variable for Current Session
Environment variable are stored in Windows Registery. [Microsoft Windows Registry Tutorial] When PowerShell starts, in reads the Registry and export them into current session of PowerShell.
Show Environment Variable Value
List environment variables:
Show env vars whose name contains “path”:
Show value of “path”:
Set/Remove Environment Variable in Current Session
Sets a env var named abc for current session:
$env:abc = "alice"
Get value of a env var:
Deleting a env var from the current session:
# adding path to the path env var $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:
[System.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.
If you have a question, put $5 at patreon and message me.