Environment Variables

To list all the environment variables use: Get-Childitem env: (or just dir env:)

Each environment variable is an object that can be retrieved with Get-Childitem (or Get-Item) and enumerated with Get-Member

Display Environment Variables

Display the value of the COMPUTERNAME environment variable:

Get-Childitem env:computername

Display the values of all environment variables:

Get-Childitem env:

gci env: | sort name

Enumerate all the environment variables:

get-childitem -path env:* | get-member

This is easier if you first set-location (cd) to the Env: Drive

cd env:

Then to display a variable: get-childitem computername

Returning a string value with $env:
PowerShell can also address environment variables using the syntax $env:variable-name this had the advantage of returning a sytem.string rather than the DictionaryEntry object returned by get-item or gci.

$env:computernameor$result = $env:computername
$result

Similarly:

$windows_path = $env:Path
$windows_path -split ';'

$powershell_path = $env:PSModulePath
(PSModulePath lists all the paths that PowerShell searches for modules and includes in its module auto-loading.)

Set Environment Variables

In an expression use this syntax: $env:VariableName = 'new-value'

For example, to append "finance" to the value of the TEAMS environment variable:

When you change environment variables, the change affects only the current session, much like using the SET command in Windows. To make the changes permanent, you can change them in the registry or with a utility like SETX or with a .Net function. You must also have permission to change the values. Permanent changes will only affect future sessions.

Delete Environment Variables

Setting a variable = an empty string will remove it completely:

$env:VariableName = ''

SET command (PowerShell function)

Here is a function to quickly list and set environment variables, like the Windows CMD SET command (by Wes Haggard)

PowerShell Providers

In addition to environment variables, PowerShell providers also provide access to other data and components in a similar way - resembling a file system drive. This allows you to access many different types of data in a consistent way.