Set an Environment Variable in Windows – Command Line and Registry


To totally unlock this section you need to Log-in


Login

Environment variables are not often seen directly when using Windows. However there are cases, especially when using the command line, that setting and updating environment variables is a necessity. In this series we talk about the various approaches we can take to set them. In this article we look at how to interface with environment variables using the Command Prompt and Windows PowerShell. We also note where in the registry the environment variables are set, if you needed to access them in such a fashion.

Print environment variables

You can use environment variables in the values of other environment variables. It is then helpful to be able to see what environment variables are set already. This is how you do it:

Command Prompt

Here's how to list all environment variables:

Command Prompt - C:\>

set

Output

ALLUSERSPROFILE=C:\ProgramData
APPDATA=C:\Users\user\AppData\Roaming

.
windir=C:\Windows

Print a particular environment variable:

Command Prompt - C:\>

echo %ProgramFiles%

Output

C:\Program Files

Windows PowerShell

Here's how to list all environment variables:

Windows PowerShell - PS C:\>
Get-ChildItem Env:

Output

Set an Environment Variable in Windows - Command Line and Registry

Print a particular environment variable:

Windows PowerShell - PS C:\>
echo $Env:ProgramFiles

Output

C:\Program Files

Set Environment Variables

To set persistent environment variables at the command line, we will use setx.exe. It became part of Windows as of Vista/Windows Server 2008. Prior to that, it was part of the Windows Resource Kit. If you need the Windows Resource Kit, see Resources at the bottom of the page.

setx.exe does not set the environment variable in the current command prompt, but it will be available in subsequent command prompts.

User Variables

Command Prompt - C:\>
setx EC2_CERT "%USERPROFILE%\aws\cert.pem"

Open a new command prompt.

Command Prompt - C:\>
echo %EC2_CERT%

Output

C:\Users\user\aws\cert.pem

System Variables

To edit the system variables, you will need an administrative command prompt (cmd.exe).

Command Prompt - C:\>
setx EC2_HOME "%APPDATA%\aws\ec2-api-tools" /M

Registry

Warning: this method is recommended for experienced users only.

User Variables

The location of the user variables in the registry is: HKEY_CURRENT_USER\Environment.

System Variables

The location of the system variables in the registry is:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment