PowerShell: Set Environment Variable

By Xah Lee. Date: . Last updated: .

This page is a tutorial on using PowerShell to view or set environment variables.

For introduction on Microsoft Windows Environment Variables, see: Windows Environment Variable Tutorial .

Windows environment variable names are case-insensitive.

Environment variable are stored in Windows Registry. [see Windows: Registry Tutorial] When PowerShell starts, it reads the Registry and export them into current session of PowerShell.

Adding Path to Path Environment Variable

Environment Variable in Current Session

List Environment Variables

List environment variables:

dir env:
powershell env var 2021-01-24

Show env vars whose name contains “path”:

dir env:*path*

Set Environment Variable for current session

Sets a env var named abc for current session:

$env:abc = "alice"

Get value of a env var:

$env:abc

Remove Environment Variable for current session

Deleting a env var from the current session:

rm env:abc

Permament Environment Variable

Permanent environment variable is stored in Windows Registry. [see PowerShell: 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 env: provider.

To manipulate env var in the registry, use the .NET object like the following:

View

Show env var named “path” of the category “User”:

[environment]::GetEnvironmentVariable("path", "User")

The possible values for the second argument in GetEnvironmentVariable are:

"Process"
Current session of PowerShell.
"User"
Permanent, environment variable for current user. Stored in Registry.
"Machine"
Permanent, environment variable for this machine. Stored in Registry. Require admin privilege.

Create/Set environment variable in Registry

Examples of creating/setting a environment variable:

[Environment]::SetEnvironmentVariable("xx", "123", "User")
# or
[Environment]::SetEnvironmentVariable("xx", "123", "Machine")

The syntax [Environment]::SetEnvironmentVariable means calling the .NET object “Environment” and using its method “SetEnvironmentVariable”.

Note: all arguments should be string.

Remove environment variable in Registry

# removing a env var from registry
[Environment]::SetEnvironmentVariable("xyz", $null, "User")
# or
[Environment]::SetEnvironmentVariable("xyz", $null, "Machine")

Refresh

changes of environment variable in registry is not reflected in current PowerShell session. type exit to exit PowerShell, then start a new session.