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 variable, see: Windows Environment Variables Tutorial .

Windows environment variable names are case-insensitive.

Environment variable are stored in Windows Registery. [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

Show the value of environment variable path:

$env:path -split ";"

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

[Environment]::SetEnvironmentVariable("path", $env:path + ";c:/Users/xah/bin/", "User")

restart PowerShell to see the new value.

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*

Show value of “path”:

$env:path -split ";"
PowerShell path env 2021-03-05

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. 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", "something", "User")

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

note: all arg should be string.

Remove environment variable in Registry

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

Refresh

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

PowerShell

Practical How-To

PowerShell in Depth

Programing PowerShell

Script Examples