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

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 -split ";"
PowerShell path env 2021-03-05
PowerShell path environment variable value

Set 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

Remove Environment Variable in Current Session

Deleting a env var from the current session:

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

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

PowerShell

How-to

Advanced

Script Examples