PowerShell: View/Set Environment Variables

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 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

powershell env var 2021-01-24
powershell env var 2021-01-24

List environment variables:

Get-ChildItem env:

Show env vars whose name contains “path”:

Get-ChildItem env:*path*

Show value of “path”:

$env: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:

$env:abc

Deleting a env var from the current session:

Remove-Item env:abc
# 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 env: provider.

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

View

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

[environment]::GetEnvironmentVariable("xyz", "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

Creates environment variable $xyz of category “User”, and set the value to "3".

[Environment]::SetEnvironmentVariable("xyz", "3", "User")

The syntax [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")

Remove

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

Refresh

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.

PowerShell

xah powershell logo

More Advanced