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




ls env:

Get environment variable


set {name}
set TMP







Set environment variable


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


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:


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.


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


    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 🙂


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 )

Connecting to %s