Quick tip: Access local environment variables

Just a quick tip on how to get and set environment variables using PowerShell, compared to how it is done in DOS.

List all environment variables

DOS

set

PowerShell

ls env:

Get environment variable

DOS

set {name}
set TMP

or

%{name}%
%TMP%

PowerShell

$env:{name}
$env:TMP

or

[Environment]::GetEnvironmentVariable("{name}")
[Environment]::GetEnvironmentVariable("TEST")

Set environment variable

DOS

set {name}={value}
set TEST=test

PowerShell

new-item -name {name} -path env: -value {value}
new-item -name TEST -path env: -value test

About scope

Keep in mind that these methods for managing environment variables are done in the context of the current user, and will only live in the current session. The environment variables are actually a mix of system and user environment variables, and can be found in the registry at these locations:

  • Computer\HKEY_CURRENT_USER\Environment (User)
  • Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment (System)
When you open CMD or PowerShell these are read to memory and can be accessed in the ways described above.
If you need to make a new permanent environment variable, you need to use the .NET SetEnvironmentVariable method.
[Environment]::SetEnvironmentVariable("TestVariable", "Test value.", "User")

Here you see that we pass in the variable scope as a parameter to the method (“User” in this example, other valid values are “Machine” or “Process”).

You can also use the GetEnvironmentVariable to read environment variables from a specific “scope”. Consider the following examples:

[Environment]::GetEnvironmentVariable("Username")
[Environment]::GetEnvironmentVariable("Username","Process")
[Environment]::GetEnvironmentVariable("Username","Machine")

As we can learn from this, the default scope is Process. If we ask for the same variable from the machine scope (or level), we get SYSTEM instead, because it’s read in the context of the machine.

2 comments

  1. Please post more expanded topic about scope of those variable. My understanding those are User ones and hence might lead to some confusion during script development when environment variables are set/read by processes running under different accounts (happened to me more the once).

    Like

    1. Good point Gregory. Going to add a small section about this at the end of the post. I’m not an expert on environment variables, so feel free to let me know if something is wrong, or missing 🙂

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s