Windows environment variables user variables

system environment variables

Windows uses environment variables to store valuable information about system processes, resource usage, file path, and more.

Let’s learn how to set up system environment variables in Windows.

What are Environment Variables in Windows?

Environment variables help Windows set up a software environment and act as information containers for all applications running on the operating system. Imagine an application that wants to know the path to a specific file on your computer. The program can either go through the entire system and keep searching until it finds the file. A more innovative way is to call the PATH environment variable that contains the paths to all the system files.

Moreover, system environment variables also affect the installation of Java Development Kit, Java Runtime Environment, and other essential software. Just like the above examples, there are a plethora of small and extensive real-world use cases of environment variables that overall make Windows a snappier version of itself.

Types of Environment Variables

Windows creates and uses several environment variables, some of which are user-dependent and others remain the same for all users on a single machine. We can categorize environment variables using user dependence as a parameter and term them as system environment variables and user environment variables.

Information like the location of temporary files from an account, location of your user profile, etc., are stored under user variables. Windows gives the user account the privilege to edit the user variables, but other user accounts cannot edit them.

Other than this, Windows contains system environment variables created by the operating system, programs, drivers, and more. You cannot tweak the system environment variables, but Windows offers the option to tweak user environment variables’ values.

Methods to Setup System Environment Variables in Windows

You can set up system environment variables using different methods in Windows. Although the command line methods remain unchanged for all Windows versions, the GUI-based methods differ slightly for different Windows versions. Let’s look at all these methods in-depth.

GUI Based Methods

The GUI-based methods include using the Start search menu, the Run Window, and the Settings menu to tweak system environment variables. Let’s look at how you can access the GUI from various Windows versions.

Steps for Windows 11

Click on the Start Menu and search for “environment variables.”

The “Edit the system environment variables” option will appear in the search results. Click on the same, and Windows 11 will display the list of all environment variables.

Steps for Windows 10

Go to settings and enter the “About” menu.

Now go to “Advanced system settings.” The System Properties dialogue box should appear on your screen.

Click on the “Advanced” tab and select “Environment Variables.” Windows 10 will now display the entire list of user and system variables stored on your computer.

Using Run Window

Press Windows +R to explore the Run Window.

Now enter the following command:

rundll32.exe sysdm.cpl,EditEnvironmentVariables

system environment variable

All these methods should open the list of all the environment variables categorized under separate sections for user and system environment variables. You can create new user variables, edit the existing ones, or delete them using the same dialogue box.

Steps to create a new environment variable

Click on the “New” option using the Environment Variables dialogue box.

Now enter the Variable Name and its Value under the respective columns and press OK.

Creating the JAVA_HOME environment variable is a crucial step for installing Java Development Kit. So, let’s create the JAVA_HOME variable and later verify its existence. Click on the New option and enter “JAVA_HOME” as the variable name. Also, enter the installation path for the JDK as the variable value for JAVA_HOME.

The JAVA_HOME variable is now visible on the list of all environment variables, with the variable value as the path to the JDK. You can verify it by going to the “edit system variable” settings, and the JAVA_HOME variable should be present right there.

Steps to Edit environment variables

Click on the environment variable you want to edit and press the “Edit” option.

Now enter the Variable Name and its Value and press the OK button.

Let’s now edit the JAVA_HOME variable that we just created and change its value to another folder. Click on the variable and select the “Edit” option. Now enter a different variable value replacing the previous value and click OK.

Here also, you can verify the changed value on the environment variable list.

The updated variable is present on the user variable list.

Steps to Delete environment variables

Click on the environment variable you want to Delete.

Now Press the “Delete” option and press OK.

As an example, let’s delete the JAVA_HOME variable that we recently tweaked. Select the variable and press “Delete” and “OK” subsequently. The selected variable gets deleted from the list of variables.

The JAVA_HOME variable gets deleted from the list.

Command Prompt Method

You can use the Command Prompt or Windows PowerShell to set up environment variables. Let’s first look at how to use the command prompt method.

Viewing the environment variables

Open the command prompt in Windows.

Now enter “set” and press Enter. You can see the entire list of environment variables without any categorization, unlike the GUI-based method.

Creating new environment variables

Open the command prompt.

Use the following syntax using the setx command and press Enter:

setx [variable_name] “[variable_value]”

[variable_name] stands for the name of the variable you want to enter.

[variable_value] stands for the value for the newly created variable.

For example, let’s create a “TEST_VARIABLE” with a value “XYZ” and then verify its existence using Command Prompt. We use the following command:

setx [TEST_VARIABLE] “[XYZ]”

Congratulations! You just created a new user variable using Command Prompt. Now, let’s verify its existence. Use the “set” command to see the list of all the variables.

Windows PowerShell Method

PowerShell gives you more flexibility with the environment variables and lets you view, edit, and create them, but these are only valid for a single PowerShell session. The variable list returns to its original form once you close a PowerShell session.

Viewing system variables

Open the Windows PowerShell.

Now enter the following command:

Get-ChildItem Env:

Windows PowerShell will display the complete list of environment variables.

The environment variables won’t get categorized under system and user variables, but you can use the following commands to only view system variables using PowerShell:

[Environment]::GetEnvironmentVariables("Machine")

Otherwise, you can use the following command to only view the user environment variables:

[Environment]::GetEnvironmentVariables("User")

Creating and Editing environment variables

You can edit and create new environment variables using the $env built-in variable. Use the following command to create a new variable using PowerShell:

$env:Variable_name = 'Variable_value'

Here Variable_name stands for the name of the newly created environment variable, and the variable_value stands for its value.

Let’s create another test variable TEST_VARIABLE as an example and then verify its existence. We use the following command in the PowerShell:

$env:TEST_VARIABLE = '[ABC]'

We have also confirmed the variable value for TEST_VARIABLE using the following code:

$env:TEST_VARIABLE

PowerShell shows the output for the TEST_VARIABLE variable as [ABC].

Moreover, you can also tweak the value for an existing environment value using the following command:

$env:Variable_name = ';Variable_value2'

This would append the newly mentioned value to the original value for the environment variable.

Conclusion 🧑‍💻

Creating and tweaking system environment variables is crucial to direct programs and utilize their functionality. Windows gives you GUI-based and Command Line options to do the same. The GUI-based methods are simple and easy to follow. On the other hand, the Command-Line methods are swifter but more complicated.

Now you may check Tuning MySQL system variables for high performance.

System and User Environment Variables has always been a complex topic of discussion for day-to-day Windows OS users. What do they do? A tutorial on the internet said to add a PATH variable, but what is it? Where do I find these variables? All of these questions will be shortly answered in this post. We’ve tried to give you a high-level overview of what System and User Environment Variables are and how you can utilize them.

In this post, we will discuss Environment Variables, System and User Environment Variables and how to add and modify them. Then we will move on to Dynamic System Variables and see how to use them in the command prompt.

What is an Environment Variable In Windows OS

Environment Variable is formed up by two separate words, ‘Environment’ and ‘Variable’. Let’s discuss ‘variable’ first. It means that the entity can store a value and vary from computer to computer. Windows provide an ‘Environment’ for applications to execute and perform operations and that is what makes the first word. Combining both, Environment Variables are those dynamic objects that store the values provided by the environment. Now environment provides values that help other programs in obtaining some crucial information about the system. Like there is an environment variable called ‘windir’ that corresponds to the directory where Windows is installed. To see this in action, open up an explorer window and type in ‘%windir%’ in the address bar. The Windows installation folder will open up.

Very similarly, you can make reference to the Windows directory using ‘windir’ variable in other programs and scripts. There are numerous other variables that can be accessed, ‘TEMP’ or ‘TMP’ is the variable that points to the directory where all temporary files are stored. The most popular, ‘Path’ variable is the one that points to the directories containing executable files. So that you can run a program from the Command Prompt in any other directory. We’ve explained Path later on in this post. All these variables come in handy when you are developing something or using the shell a lot.

Very similar to how the Registry works on Windows, we have System and User Environment Variables. The system variables are system-wide accepted and do not vary from user to user. Whereas, User Environments are configured differently from user to user. You can add your variables under the user so that other users are not affected by them.

Just for your information since we are discussing the topic in depth. System Variables are evaluated before User Variables. So if there are some user variables with the same name as system variables then user variables will be considered. The Path variable is generated in a different way. The effective Path will be the User Path variable appended to the System Path variable. So the order of entries will be system entries followed by user entries.

How to add & modify Environment Variables

A small warning before we go deeper. Create a system restore point, and try not to tamper with the existing settings configured for your system. Until unless you are very sure about your actions. To open the ‘Environment Variables’ Window, follow these steps:

  1. Right-click ‘This PC’ icon and select ‘Properties’.
  2. Now in this window select ‘Advanced System Settings’ from the left part.
  3. Hit the last button saying ‘Environment Variables’ to open our destined window.

System & User Environment Variables

Once you’ve opened this up, you will be able to view User and System variables separately. The variable name is in the first column and its value in the second. The corresponding buttons below the table let you ‘Add’, ‘Edit’ and ‘Delete’ these variables.

Using the Path variable

Path is the most used environment variable. As I mentioned, it points to directories that contain executable files. Once you’ve correctly setup your Path variable, you can use these executables from anywhere in the system. Let’s try to understand this with an example. Open up the environment variables window and look for ‘Path’ in system variables.

System & User Environment Variables

Click on ‘Edit’ and then click on ‘New’ without playing around with other controls right now. Now click browse and select a folder that has your desired executable file. Click ‘Ok’ and save everything. I added ‘Visual Studio Code’ executable to the path.

Now to run your application, open up Command Prompt and type in the name of the executable file that was in the folder. You can provide additional arguments if the program supports it. The program will run from the command prompt without actually being in the directory from where you executed the command. That is the beauty of the Path variable.

Read: How to add or edit a PATH Environment Variable in Windows.

List of all Environment Variables

Open command prompt and type ‘SET’ and hit Enter. The entire list of variables with their current values will be displayed and you can refer to it for making changes to your computer.

Read: How to see Names and Values of Environment Variables in Windows

Dynamic Environment Variables

Unlike, conventional variables, dynamic environment variables are provided by the CMD and not by the system. You cannot change the values of these variables and they expand to various discrete values whenever queried. We usually use these variables for batch processing and these are not stored in the environment. Even the ‘SET’ command will not reveal these variables. Some of the dynamic environment variables are listed below.

Read: How to add Environment Variables to Context Menu.

List of environment variables in Windows 11/10

%APPDATA% – C:\Users\<username>\AppData\Roaming

%ALLUSERSPROFILE% – C:\ProgramData

%CD% – Typing in this command will give you the current directory you are working in.

%COMMONPROGRAMFILES% – C:\Program Files\Common Files

%COMMONPROGRAMFILES(x86)% –  C:\Program Files (x86)\Common Files

%COMMONPRGRAMW6432% –  C:\Program Files\Common Files

%CMDEXTVERSION% – This variable expands to the version of the command-line extensions.

%COMSPEC% – C:\Windows\System32\cmd.exe

%DATE%: – This variable will give you the current date according to date format preferences.

%ERRORLEVEL% – Determines the error level set by last executing command.

%HOMEDRIVE%  – C:\

%HOMEPATH%  -C:\Users\<username>

%LOCALAPPDATA% – C:\Users\<username>\AppData\Local

%LOGONSERVER% – \\<domain_logon_server>

%PATH% – C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem

%PATHEXT% – .com;.exe;.bat;.cmd;.vbs;.vbe;.js;.jse;.wsf;.wsh;.msc

%PROGRAMDATA% – C:\ProgramData

%PROGRAMFILES% – C:\Program Files

%PROGRAMW6432% – C:\Program Files

%PROGRAMFILES(X86)% – C:\Program Files (x86)

%PROMPT% – $P$G

%SYSTEMDRIVE% – C:

%SYSTEMROOT% – C:\Windows

%TIME% – Similarly, it gives you current time according to the time format preferences.

%TMP% – C:\Users\<username>\AppData\Local\Temp

%TEMP% – C:\Users\<username>\AppData\Local\Temp

%USERNAME% – <username>

%USERPROFILE% – C:\Users\<username>

%USERDOMAIN% – Userdomain associated with current user.

%USERDOMAIN_ROAMINGPROFILE% – Userdomain associated with roaming profile.

%WINDIR%  – C:\Windows

%PUBLIC% – C:\Users\Public

%PSMODULEPATH% – %SystemRoot%\system32\WindowsPowerShell\v1.0\Modules\

%ONEDRIVE%  – C:\Users\<username>\OneDrive

%DRVERDATA%  – C:\Windows\System32\Drivers\DriverData

%CMDCMDLINE%  – Outputs command line used to launch the current Command Prompt session. (Command Prompt.)

%COMPUTERNAME%  -Outputs the system name.

%PROCESSOR_REVISION% – Outputs processor revision.

%PROCESSOR_IDENTIFIER%  – Outputs processor identifier.

%PROCESSOR_LEVEL%  – Outputs processor level.

%RANDOM% – This variable prints a random number from 0 through 32767

%NUMBER_OF_PROCESSORS% – Outputs the number of physical and virtual cores.

%OS% – Windows_NT

This was pretty much about System and User Environment Variables on Windows. Windows does come with a lot more variables – don’t forget to check them using the ‘SET’ command.

TIP: Rapid Environment Editor is a powerful Environment Variables Editor for Windows.

Most operating systems have environment variables, including Windows, MacOS, and Linux. Just like in a programming language, environment variables can be called upon to use their values that can store a number, a location, or any other value defined.

The environment variables were introduced with Windows 95, and have since gone through many iterations with every Windows release. These can be used to access certain directories quickly, rather than enter the complete paths.

Environment variables can be edited and manipulated, or you can even add new ones. In this article, we discuss the many different Windows environment variables and what they do, and all that you need to know about them.

This guide applies to all versions of Windows, including Windows XP, Windows Vista, Windows 7, Windows 8, Windows 10, and Windows 11.

Table of contents

  • What are Environment Variables
  • What are Environment Variable Scopes
    • System/Machine
    • User
    • Process
  • Complete list of Windows Environment Variables
  • Where are Environment Variables Stored
  • How to View/Access Windows Environment Variables
    • Access Environment Variables from Settings App
    • Access Environment Variables from Command Line
    • List Environment Variables in PowerShell
    • View Value for Environment Variable using Command Prompt
  • How to Create and Set Environment Variables in Windows
    • From System Properties
    • From Command Prompt
      • Temporary Environment Variable
      • Permanent Environment Variable
  • How to Delete an Environment Variable in Windows
  • How to Edit an Environment Variable in Windows
  • What is the PATH Environment Variable
  • How to Manage Environment Variables using PowerShell Env
  • Frequently Asked Questions (FAQs)
    • Is it safe to delete an environment variable?
    • What does the PATH environment variable do?

What are Environment Variables

Environment variables are variables that can be used across your system. Just like in programming, variables contain a value that can be changed or called when needed. Environment variables are the same, but can be used across the entire scope.

You can use environment variables in Windows to store frequently used locations, so you don’t have to type them out each time, or temporarily change the way a program behaves. Environment variables are normally used in scripts or programs/apps.

For example, you can create an environment variable called TEMP that points to a different folder than the default TEMP folder Windows uses. Then, when a program needs to store temporary files, it will use the TEMP folder you specified instead of the default one.

Tip: If you are using Linux or MacOS, the environment variables can be set in the .bashrc or .profile files.

There are 3 types/scopes of environment variables in the hierarchy:

  1. Machine
  2. User
  3. Process

At the top, you have machine or system environment variables. This can be used across the entire system, regardless of which user is logged in. Then there are user environment variables. This is defined individually for each user account and is limited to that account only.

Then you have the process variables which are only limited to the processes and cannot be edited or created. The end-user does not see or have anything to do with the process variables.

Additionally, if there is an environment variable of the same name in more than one scope, then the variable in the lower scope will supersede the value of the one higher in the hierarchy.

For example, the common environment variable “TEMP” is available in all scopes with the following values:

  • Machine: C:\Windows\Temp
  • User: C:\Users\[Username]\AppData\Local\Temp
  • Process: C:\Users\[Username]\AppData\Local\Temp

Hence, using the “Temp” variable will call for the value set for the process scope. If there is no variable by the name “Temp” in this scope, then it will use the value for the user scope, and so on.

You can use these variables to access a directly quickly. For example, typing in “%HOMEPATH%” in the Run Command box will open the user’s home directory.

homepath variable

Using an environment variable

You can also edit this variable to include a sub-directory of the path, like opening the user account’s desktop by typing in “%HOMEPATH%\Desktop%”.

homepath desktop variable

Using an environment variable to open its subdirectory

What are Environment Variable Scopes

As we mentioned earlier, there are 3 scopes for environment variables: Machine/System, user, and process. These scopes define the limitations of the variables and where they can be used.

Below you’ll find a more detailed explanation of the different types of environment variable scopes.

System/Machine

The environment variables defined inside this scope can be used by anyone on the system. These types of variables are associated with the running instance of Windows. Any user account can read these, set, change, or delete them, provided they have administrative rights.

User

The environment variables defined within this scope are only user-specific and might be different for each user account. This is associated with the current user. User variables overwrite machine-scoped variables with the same name.

Process

Environment variables in this scope are a combination of machine and user scopes in addition to some dynamically-created variables by the Windows OS.

Now that you know what environment variables are and how they work, let us see which variables are available in a Windows OS.

Here is a list of the process variables which are available in this scope:

  • ALLUSERSPROFILE
  • APPDATA
  • COMPUTERNAME
  • HOMEDRIVE
  • HOMEPATH
  • LOCALAPPDATA
  • LOGONSERVER
  • PROMPT
  • PUBLIC
  • SESSION
  • SystemDrive
  • SystemRoot
  • USERDNSDOMAIN
  • USERDOMAIN
  • USERDOMAIN_ROAMINGPROFILE
  • USERNAME
  • USERPROFILE

Complete list of Windows Environment Variables

Below is a complete list of the environment variables that you will find inside the Windows operating system by default:

Windows Environment Variables Opt

Default Windows Environment Variables
Variable Name Value
%ALLUSERSPROFILE% C:\ProgramData
%APPDATA% C:\Users\{username}\AppData\Roaming
%COMMONPROGRAMFILES% C:\Program Files\Common Files
%COMMONPROGRAMFILES(x86)% C:\Program Files (x86)\Common Files
%CommonProgramW6432% C:\Program Files\Common Files
%COMSPEC% C:\Windows\System32\cmd.exe
%HOMEDRIVE% C:\
%HOMEPATH% C:\Users\{username}
%LOCALAPPDATA% C:\Users\{username}\AppData\Local
%LOGONSERVER% \\{domain_logon_server}
%PATH% C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem
%PathExt% .com;.exe;.bat;.cmd;.vbs;.vbe;.js;.jse;.wsf;.wsh;.msc
%PROGRAMDATA% C:\ProgramData
%PROGRAMFILES% C:\Program Files
%ProgramW6432% C:\Program Files
%PROGRAMFILES(X86)% C:\Program Files (x86)
%PROMPT% $P$G
%SystemDrive% C:
%SystemRoot% C:\Windows
%TEMP% C:\Users\{username}\AppData\Local\Temp
%TMP% C:\Users\{username}\AppData\Local\Temp
%USERDOMAIN% Userdomain associated with the current user.
%USERDOMAIN_ROAMINGPROFILE% Userdomain associated with roaming profile.
%USERNAME% {username}
%USERPROFILE% C:\Users\{username}
%WINDIR% C:\Windows
%PUBLIC% C:\Users\Public
%PSModulePath% %SystemRoot%\system32\WindowsPowerShell\v1.0\Modules\
%OneDrive% C:\Users\{username}\OneDrive
%DriverData% C:\Windows\System32\Drivers\DriverData
%CD% Outputs current directory path. (Command Prompt.)
%CMDCMDLINE% Outputs command line used to launch current Command Prompt session. (Command Prompt.)
%CMDEXTVERSION% Outputs the number of current command processor extensions. (Command Prompt.)
%COMPUTERNAME% Outputs the system name.
%DATE% Outputs current date. (Command Prompt.)
%TIME% Outputs time. (Command Prompt.)
%ERRORLEVEL% Outputs the number of defining exit status of the previous command. (Command Prompt.)
%PROCESSOR_IDENTIFIER% Outputs processor identifier.
%PROCESSOR_LEVEL% Outputs processor level.
%PROCESSOR_REVISION% Outputs processor revision.
%NUMBER_OF_PROCESSORS% Outputs the number of physical and virtual cores.
%RANDOM% Outputs random numbers from 0 through 32767.
%OS% Windows_NT
List of all Windows Environment Variables

Where are Environment Variables Stored

The environment variables are stored in 2 places in the Windows Registry; one for the system and one for individual users.

The system environment variables are stored at the following location:

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

System environmental variables in Windows Registry

System environment variables in Windows Registry

The user environment variables are stored at the following location:

Computer\HKEY_CURRENT_USER\Environment

User environmental variables in Windows Registry

User environment variables in Windows Registry

You can also export the “Environment” key using its context menu to import the environment variables on another Windows computer, or vice versa.

Now that you know where they are stored, you may have a look at them. However, it is strongly recommended that you do not add or change environment variables using the Windows Registry. This is because any running processes will not see variable changes in the registry. Processes only see the registry variables and values that are present when the process was started unless Windows notifies them that there has been a change.

If you want to add or make changes to the environment variables, keep reading this post.

How to View/Access Windows Environment Variables

You can view and access Windows environment variables in multiple ways. Pick the method you like best from below.

Access Environment Variables from Settings App

Follow these steps to access the environment variables using the Settings app:

  1. Navigate to the following:

    Settings app >> System >> About
  2. Now click Device Specifications to expand it.

    Expand Device Specifications

    Expand Device Specifications
  3. Now click Advanced system settings under Related links.

    Open Advanced system settings

    Open Advanced system settings
  4. From the pop-up System Properties window, switch to the Advanced tab, and then click Environment Variables.

    Open Environmental Variables

    Open Environment Variables
  5. The Environment Variables window will now open. Here, you can see the user variables at the top and the system/machine variables at the bottom.

    Environmental Variables window

    Environment Variables window

Access Environment Variables from Command Line

If you want to access the environment variables using the Command Line, here is how:

  1. Run the following cmdlet in either the Command Prompt, Windows PowerShell, or the Run Command box to open the System Properties applet.

    sysdm.cpl

    sysdm

    Open System Properties applet
  2. From the pop-up System Properties window, switch to the Advanced tab, and then click Environment Variables.

    Open Environmental Variables2

    Open Environment Variables
  3. The Environment Variables window will now open. Here, you can see the user variables at the top and the system/machine variables at the bottom.

    Environmental Variables window2

    Environment Variables window

List Environment Variables in PowerShell

Alternative to the methods discussed above, you can also list the environment variables in PowerShell using a simple cmdlet.

Run the following command in an elevated PowerShell instance and it will display all of the environment variables on your computer:

Get-ChildItem Env: | Sort Name

List environmental variables in PowerShell

List environment variables in PowerShell

View Value for Environment Variable using Command Prompt

If you access the environment variable using any of the given methods above, then you can see their values as well. Another method to view the value of an environment variable is through the Command Prompt.

Simply type in “echo” followed by the environment variable name in the “%” sign in an elevated Command Prompt and you will then see its value(s), as in this image:

Display environment variable value

Display environment variable value

How to Create and Set Environment Variables in Windows

From System Properties

You may need to create a new environment variable or modify an existing one in the Windows OS to be used for programming purposes or to use Java. Whatever the reason, follow these steps to create a new environment variable using the GUI:

  1. Access the Environment Variables window using one of the given methods above. In this window, click New either under user variables or system variables, depending on which scope you want to create the variable in.

    Create a new varibale

    Create a new variable
  2. In the popup window, set a name for the variable and then enter its value. Once done, click Ok.

    Enter details for variable

    Enter details for variable
  3. Back in the Environment Variable window, click OK again to save the changes.

The variable will now be created, and you can now use it in your code, or access the folder by concatenating a “%” sign on the front and back of it.

Access path using environmental vairable

Access path using environment variable

From Command Prompt

You can also create a new environment variable using the Command Prompt, and define its value(s). You can create both a temporary variable that only lasts until the instance is closed or the system is rebooted, or a permanent variable that will always remain unless explicitly deleted.

Once you create the variable, you can access it immediately. There’s no need to restart the computer for the changes to take effect.

Note: These methods create a user environment variable and not a system variable.

Temporary Environment Variable

Use the following cmdlet in an elevated Command Prompt to create a temporary variable while replacing [VariableName] with a custom name for the variable, and [Value] with the value that you want to define for the variable, which can be a string or a number.

Set [VariableName]=[Value]

Create new environment variable using Command Prompt

Create new environment variable using Command Prompt

Permanent Environment Variable

If you want to create a permanent environment variable, then use this cmdlet instead:

Setx [VariableName] "[Value]"

Permanent variable created using Command Prompt

Permanent variable created using Command Prompt

How to Delete an Environment Variable in Windows

If you no longer need an environment variable, you can simply delete it.

One concern while deleting a variable is whether it is safe. The answer is both yes and no. Nothing happens when an environment variable is deleted, except that the apps, program, and other elements no longer know where to look for an item when it is called upon. Other than that, it has no impact on the system’s performance.

That said, we still think that you should be extremely careful when deleting a variable. If you still wish to continue to remove an environment variable, follow these steps:

Note: It is advisable that you create a system restore point before proceeding so that your system can be reverted to previous settings in case things do not go as planned.

  1. Access the Environment Variables window using one of the given methods above.

  2. In the Environment Variables window, click on the variable that you want to remove and click Delete under the same section.

    Delete environmental variable

    Delete environment variable
  3. Now click Ok to save the changes.

The variable will now be removed from your PC.

How to Edit an Environment Variable in Windows

You can also edit an environment variable. Its name can be changed as well as its value. However, it is recommended that you do not edit the default Windows environment variables, or else the apps and programs using those variables might no longer work.

That said, the “PATH” variable stores several paths to directories for executable files. You can safely add more directory paths to this variable without causing an issue.

Follow these steps to edit an environment variable in Windows:

  1. Access the Environment Variables window using one of the given methods above.

  2. Here, click on the variable that you want to edit and then click Edit under the same section.

    Edit an environmental variable

    Edit an environment variable
  3. From the Edit popup, make the changes you want to the name or the value of the variable, and then click Ok.

    Edit variable details

    Edit variable details
  4. Back on the Environment Variables window, click Ok to save the changes.

What is the PATH Environment Variable

Earlier in this post, we mentioned the PATH environment variable. The PATH variable is perhaps the most-used variable out of the lot.

The PATH variable stores multiple entries (or values). Those values specify the directories in which the executable programs are located on the system so that they can be started without knowing and typing the whole path to the file on the command line.

How to Manage Environment Variables using PowerShell Env

The PowerShell has a virtual drive known as the “PS Drive.” It is a data store location that you can access like a file system drive in Windows PowerShell. Using this drive, we can manage different aspects of the environment variables. A PS drive allows you to treat environment variables as if they are a file system through the Env: drive.

Below you’ll find the guidelines to perform different variables-related tasks using the Env: drive.

To begin, you must first switch to the ENv: drive. To do that, type in the following in the PowerShell window.

cd Env:

Enter the Env drive

Enter the Env: drive

To get the complete list of environment variables and their values, use the following cmdlet:

Get-Item -Path Env:

Get complete list of variables in Env

Get complete list of variables in Env

You can also create new environment variables from the Env: drive by using this cmdlet. Replace [VarableName] with a name for the variable, and [Value] with the value you want to set for the variable.

NewItem -Path Env:\[VariableName] -Value [Value]

Create a new variable in Env drive

Create a new variable in Env: drive

To set the value of an existing variable, use this cmdlet:

Set-Item -Path Env:[VariableName] -Value "[Value]"

Set change variable value in Env drive

Set/change variable value in Env drive

To delete an environment variable from the Env: drive, use this cmdlet:

Remove-Item -Path Env:\[VariableName]

Delete variable in Env Drive

Delete variable in Env Drive

Frequently Asked Questions (FAQs)

Is it safe to delete an environment variable?

The answer is both yes and no. Although deleting a default OS environment variable will have no performance repercussions, any apps or programs using that variable will no longer be able to look for the executables in the specified directories, or you won’t be able to use the shortcuts anywhere in the system to run an executable.

What does the PATH environment variable do?

The PATH environment variable can store multiple path values for different executable files. When an executable file is called, like “CMD,” the PATH variable tells it where to look for the cmd.exe file.

Introduction

Environment variables are key-value pairs a system uses to set up a software environment. The environment variables also play a crucial role in certain installations, such as installing Java on your PC or Raspberry Pi.

In this tutorial, we will cover different ways you can set, list, and unset environment variables in Windows 10.

How to set environment variables in Windows

Prerequisites

  • A system running Windows 10
  • User account with admin privileges
  • Access to the Command Prompt or Windows PowerShell

Check Current Environment Variables

The method for checking current environment variables depends on whether you are using the Command Prompt or Windows PowerShell:

List All Environment Variables

In the Command Prompt, use the following command to list all environment variables:

set
List all environment variables using the Command Prompt

If you are using Windows PowerShell, list all the environment variables with:

Get-ChildItem Env:
List all environment variables using Windows PowerShell

Check A Specific Environment Variable

Both the Command Prompt and PowerShell use the echo command to list specific environment variables.

The Command prompt uses the following syntax:

echo %[variable_name]%
Checking a specific environment variable using the Command Prompt

In Windows PowerShell, use:

echo $Env:[variable_name]
Checking a specific environment variable using Windows PowerShell

Here, [variable_name] is the name of the environment variable you want to check.

Follow the steps to set environment variables using the Windows GUI:

1. Press Windows + R to open the Windows Run prompt.

2. Type in sysdm.cpl and click OK.

Run sysdm.cpl

3. Open the Advanced tab and click on the Environment Variables button in the System Properties window.

Find the Environment Variables button in the Advanced tab

4. The Environment Variables window is divided into two sections. The sections display user-specific and system-wide environment variables. To add a variable, click the New… button under the appropriate section.

Click on the New... button to add a variable

5. Enter the variable name and value in the New User Variable prompt and click OK.

Enter the new variable name and value

Set Environment Variable in Windows via Command Prompt

Use the setx command to set a new user-specific environment variable via the Command Prompt:

setx [variable_name] "[variable_value]"

Where:

  • [variable_name]: The name of the environment variable you want to set.
  • [variable_value]: The value you want to assign to the new environment variable.

For instance:

setx Test_variable "Variable value"
Setting a user-specific environment variable via the Command Prompt

Note: You need to restart the Command Prompt for the changes to take effect.

To add a system-wide environment variable, open the Command Prompt as administrator and use:

setx [variable_name] "[variable_value]" /M
Setting a system environment variable via the Command Prompt

Unset Environment Variables

There are two ways to unset environment variables in Windows:

Unset Environment Variables in Windows via GUI

To unset an environment variable using the GUI, follow the steps in the section on setting environment variables via GUI to reach the Environment Variables window.

In this window:

1. Locate the variable you want to unset in the appropriate section.

2. Click the variable to highlight it.

3. Click the Delete button to unset it.

Unset environment variables in Windows via GUI

Unset Environment Variables in Windows via Registry

When you add an environment variable in Windows, the key-value pair is saved in the registry. The default registry folders for environment variables are:

  • user-specific variables: HKEY_CURRENT_USEREnvironment
  • system-wide variables: HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment

Using the reg command allows you to review and unset environment variables directly in the registry.

Note: The reg command works the same in the Command Prompt and Windows PowerShell.

Use the following command to list all user-specific environment variables:

reg query HKEY_CURRENT_USEREnvironment
Listing all user-specific environment variables in the registry

List all the system environment variables with:

reg query "HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment"
Listing all system environment variables in the registry

If you want to list a specific variable, use:

reg query HKEY_CURRENT_USEREnvironment /v [variable_name]
Listing a specific user environment variable in the registry

or

reg query "HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment" /v [variable_name]
Listing a specific system environment variable in the registry

Where:

  • /v: Declares the intent to list a specific variable.
  • [variable_name]: The name of the environment variable you want to list.

Use the following command to unset an environment variable in the registry:

reg delete HKEY_CURRENT_USEREnvironment /v [variable_name] /f
Unsetting a user-specific environment variable from the registry

or

reg delete "HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment" /v [variable_name] /f
Unsetting a system environment variable from the registry

Note: The /f parameter is used to confirm the reg delete command. Without it, entering the command triggers the Delete the registry value EXAMPLE (Yes/No)? prompt.

Run the setx command again to propagate the environment variables and confirm the changes to the registry.

Note: If you don’t have any other variables to add with the setx command, set a throwaway variable. For example:

setx [variable_name] trash

Conclusion

After following this guide, you should know how to set user-specific and system-wide environment variables in Windows 10.

Looking for this tutorial for a different OS? Check out our guides on How to Set Environment Variables in Linux, How to Set Environment Variables in ZSH, and How to Set Environment Variables in MacOS.

Переменные среды Windows 11 и Windows 10Настройка переменных среды Windows может помочь сократить время, необходимое для набора команд в командной строке или, если вы часто пишете скрипты для собственных задач, сделать их более читаемыми. В большинстве случаев обычные пользователи добавляют записи в системную переменную среды PATH, хотя бывают и другие задачи.

В этой пошаговой инструкции базовая информация о том, как открыть переменные среды Windows 11 и Windows 10, создать или отредактировать их.

Что такое переменные среды

Переменные среды в Windows — записи о расположении системных папок, свойствах системы и другие, которые доступны для любой программы или скрипта.

Одна из наиболее часто используемых переменных среды — PATH, указывающая на папки, в которых выполняется поиск файлов, вызываемых в командной строке, терминале Windows, файле bat или из других источников. В качестве примера её назначения:

  • Если вы откроете командную строку (или диалоговое окно «Выполнить»), введёте regedit и нажмете Enter — вы сможете запустить редактор реестра, не указывая полный путь к файлу regedit.exe, поскольку путь C:\Windows добавлен в переменную среды Path.
  • Если же тем же образом в командной строке написать имя программы, путь к которой не добавлен в Path (chrome.exe, adb.exe, pip и другие), вы получите сообщение «Не является внутренней или внешней командой, исполняемой программой или пакетным файлом».

Если предположить, что вы часто используете команды adb.exe (например, для установки приложений Android в Windows 11), pip install (для установки пакетов Python) или любые другие то для того, чтобы не писать каждый раз полный путь к этим файлам, имеет смысл добавить эти пути в переменные среды.

Также вы можете добавлять и иные переменные среды (не обязательно содержащие пути), а в дальнейшем получать и использовать их значения в сценариях BAT (командной строки) или PowerShell. Пример получения и отображения значения системной переменной PATH для обоих случаев:

echo %PATH%
echo $Env:PATH

Получить список всех переменных среды в командной строке и PowerShell соответственно можно следующими командами:

set
ls env:

Редактирование переменных среды Windows 11/10

Прежде чем приступать, учтите: изменение системных переменных среды по умолчанию может привести к проблемам в работе системы, не удаляйте уже имеющиеся переменные среды. Возможно, имеет смысл создать точку восстановления системы, если вы не уверены в своих действиях.

  1. Чтобы открыть переменные среды Windows вы можете использовать поиск в панели задач (начните вводить «Переменных» и откройте пункт «Изменение системных переменных среды») или нажать клавиши Win+R на клавиатуре, ввести sysdm.cpl и нажать Enter. Открыть изменение переменных среды в Windows
  2. На вкладке «Дополнительно» нажмите кнопку «Переменные среды…» Переменные среды в параметрах системы Windows
  3. В разделе «Переменные среды пользователя» (если требуется изменение только для текущего пользователя) или «Системные переменные» выберите переменную, которую нужно изменить и нажмите «Изменить» (обычно требуется именно это), либо, если необходимо создать новую переменную — нажмите кнопку «Создать». В моем примере — добавляем свои пути в системную переменную Path (выбираем эту переменную и нажимаем «Изменить»). Создание и изменение переменных среды Windows
  4. Для добавления нового значения (пути) в системную переменную в следующем окне можно нажать кнопку «Создать», либо просто дважды кликнуть по первой пустой строке, затем — ввести нужный путь к папке, содержащей нужные нам исполняемые файлы. Изменение переменно PATH
  5. Также вы можете использовать кнопку «Изменить текст», в этом случае окно изменения системной переменной откроется в ином виде: имя переменной, а ниже — её значение. В случае указания путей значение будет представлять собой все пути, хранящиеся в переменной, разделенные знаком «точка с запятой». Изменение имени и значения системной переменной среды
  6. При создании новой переменной среды окно будет тем же, что и в 5-м шаге: необходимо будет указать имя системной переменной в верхнем поле, а её значение — в нижнем.

После создания или изменения переменной среды и сохранения сделанных настроек, переменная или обновленные значения сразу становятся доступны для текущего пользователя или в системе в целом в зависимости от того, какие именно переменные редактировались или создавались. Также есть методы добавления переменных среды в командной строке или PowerShell, подробнее в статье: Как добавить путь в переменную среды PATH

  • Windows excel что за программа
  • Windows enterprise что это такое
  • Windows error reporting 1001 как исправить
  • Windows easy transfer for windows 10
  • Windows execute file cmd windows