Настройка переменных среды 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
Прежде чем приступать, учтите: изменение системных переменных среды по умолчанию может привести к проблемам в работе системы, не удаляйте уже имеющиеся переменные среды. Возможно, имеет смысл создать точку восстановления системы, если вы не уверены в своих действиях.
- Чтобы открыть переменные среды Windows вы можете использовать поиск в панели задач (начните вводить «Переменных» и откройте пункт «Изменение системных переменных среды») или нажать клавиши Win+R на клавиатуре, ввести sysdm.cpl и нажать Enter.
- На вкладке «Дополнительно» нажмите кнопку «Переменные среды…»
- В разделе «Переменные среды пользователя» (если требуется изменение только для текущего пользователя) или «Системные переменные» выберите переменную, которую нужно изменить и нажмите «Изменить» (обычно требуется именно это), либо, если необходимо создать новую переменную — нажмите кнопку «Создать». В моем примере — добавляем свои пути в системную переменную Path (выбираем эту переменную и нажимаем «Изменить»).
- Для добавления нового значения (пути) в системную переменную в следующем окне можно нажать кнопку «Создать», либо просто дважды кликнуть по первой пустой строке, затем — ввести нужный путь к папке, содержащей нужные нам исполняемые файлы.
- Также вы можете использовать кнопку «Изменить текст», в этом случае окно изменения системной переменной откроется в ином виде: имя переменной, а ниже — её значение. В случае указания путей значение будет представлять собой все пути, хранящиеся в переменной, разделенные знаком «точка с запятой».
- При создании новой переменной среды окно будет тем же, что и в 5-м шаге: необходимо будет указать имя системной переменной в верхнем поле, а её значение — в нижнем.
После создания или изменения переменной среды и сохранения сделанных настроек, переменная или обновленные значения сразу становятся доступны для текущего пользователя или в системе в целом в зависимости от того, какие именно переменные редактировались или создавались. Также есть методы добавления переменных среды в командной строке или PowerShell, подробнее в статье: Как добавить путь в переменную среды PATH
What is an environment variable in Windows? An environment variable is a dynamic “object” containing an editable value which may be used by one or more software programs in Windows.
In this note i am showing how to set an environment variable in Windows from the command-line prompt (CMD) and from the Windows PowerShell.
In the examples below i will set an environment variable temporary (for the current terminal session only), permanently for the current user and globally for the whole system.
Cool Tip: Add a directory to Windows %PATH%
environment variable! Read More →
Set Environment Variable For The Current Session
Set an environment variable for the current terminal session:
# Windows CMD C:\> set VAR_NAME="VALUE" # Windows PowerShell PS C:\> $env:VAR_NAME="VALUE"
Print an environment variable to the console:
# Windows CMD C:\> echo %VAR_NAME% # Windows PowerShell PS C:\> $env:VAR_NAME
Cool Tip: List Windows environment variables and their values! Read More →
Set Environment Variable Permanently
Run as Administrator: The setx
command is only available starting from Windows 7 and requires elevated command prompt. It works both for the Windows command-line prompt (CMD) and the Windows PowerShell.
Permanently set an environment variable for the current user:
C:\> setx VAR_NAME "VALUE"
Permanently set global environment variable (for all users):
C:\> setx /M VAR_NAME "VALUE"
Info: To see the changes after running setx
– open a new command prompt.
Was it useful? Share this post with the world!
- Environment variables are global system variables that are available to all users and programs running on the system. They store system-wide and user-specific values.
- You can view and manage environment variables from Settings > System > About > Advanced system settings > Environment Variables.
- To view all environment variables in Command Prompt, run “set“, or run “Get-ChildItem Env: | Sort Name” in PowerShell.
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, 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
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:
- Machine
- User
- Process
At the top, you have machine or system environment variables. These can be used across the entire system, and used for global variables, meaning changing the system variables will affect all users of the computer. Then there are user environment variables. This is defined individually for each user account and is limited to that account only and only affects the user currently logged in.
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.
Furthermore, each of these scopes has different types of variables, which are as follows:
- PATH: This variable stores a list of directories where your OS searches for executable programs. It’s crucial to run commands and launch applications from the command prompt and Run dialog.
- JAVA_HOME: This variable points to the installation directory of your Java Development Kit (JDK), a necessity for Java development and running Java applications.
- CLASSPATH: This variable tells your Java Virtual Machine (JVM) where to find user-defined classes and libraries, ensuring your Java code can access the necessary resources.
Please note that environment variables in Windows are not case-sensitive and are only written in upper case to distinguish between the variable name and the value.
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 path quickly. For example, typing in “%HOMEPATH%” in the Run Command box will open the user’s home directory.
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%”.
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:
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 |
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
The user environment variables are stored at the following location:
Computer\HKEY_CURRENT_USER\Environment
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.
View Environment Variables from Settings App
Follow these steps to access the environment variables using the Settings app:
-
Navigate to the following:
Settings app >> System >> About
-
Now click Device Specifications to expand it.
Expand Device Specifications -
Now click Advanced system settings under Related links.
Open Advanced system settings -
From the pop-up System Properties window, switch to the Advanced tab, and then click Environment Variables.
Open Environment Variables -
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.
Environment Variables window
View Environment Variables from Command Line
If you want to access the environment variables using the Command Line, here is how:
-
Run the following cmdlet in either the Command Prompt, Windows PowerShell, or the Run Command box to open the System Properties applet.
sysdm.cpl
Open System Properties applet -
From the pop-up System Properties window, switch to the Advanced tab, and then click Environment Variables.
Open Environment Variables -
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.
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 Environment Variables in Command Prompt
You can also view the list of environment variables in the Command Prompt with the following basic command:
set
This command will list down all environment variables on your computer.
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:
How to Create and Set/Edit 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:
-
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 variable -
In the popup window, set a name for the variable and then enter its value. Once done, click OK.
Enter details for variable -
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.
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]
Permanent Environment Variable
If you want to create a permanent environment variable, then use this cmdlet instead:
Setx [VariableName] "[Value]"
Using third-party software
You can also manage environment variables using third-party tools and utilities. Here are a few that can be used with great convenience.
Rapid Environment Editor
Rapid Environment Editor (REE) provides a very user-friendly way of editing environment variables. It lists the system variables in the left pane and the user variables in the right pane, while the bottom pane will give details about the selected variable.
The best thing about REE is that it will also highlight a variable if its value has some errors. You can also back up the environment variable configuration from the file menu. Rapid Environment Editor comes with an installable program, as well as a portable one. If you are using the portable REE in Windows 7 or Windows 8, you will need to run the executable in the administrative mode so that it can make changes to the system configuration.
PathMan
PathMan is a very simple portable program, which will only edit the PATH environment variable. Since PATH is a variable that needs to be edited frequently, PathMan can help edit the Path environment variable directly from the USB drive.
Eveditor
Eveditor comes with an elegant and very user-friendly graphical user interface that resembles the look and feel of Windows Explorer. You can choose from a user variable or system variable from the pane on the left. The selection will be displayed on the right-hand pane. The details of the selected environment variable will be displayed in the bottom pane.
You can edit the selected variable, and upon clicking the “Set” button, the variable will be saved. Please note that you will need to run Eveditor with administrative privileges to save the environment variables successfully.
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: You should 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.
-
Access the Environment Variables window using one of the given methods above.
-
In the Environment Variables window, click on the variable that you want to remove and click Delete under the same section.
Delete environment variable -
Now click OK to save the changes.
The variable will now be removed from your PC.
Alternatively, you can use the Command Prompt to unset an environment variable. Simply use the set
command discussed above to empty the string. Here is an example:
set [VariableName]=
Leaving the command blank after “=” will set the string to empty. The environment variable will exist but will be of no use.
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:
-
Access the Environment Variables window using one of the given methods above.
-
Here, click on the variable that you want to edit and then click Edit under the same section.
Edit an environment variable -
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 -
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:
To get the complete list of environment variables and their values, use the following cmdlet:
Get-Item -Path 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]
To set the value of an existing variable, use this cmdlet:
Set-Item -Path Env:[VariableName] -Value "[Value]"
To delete an environment variable from the Env: drive, use this cmdlet:
Remove-Item -Path Env:\[VariableName]
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.
Readers help support Windows Report. We may get a commission if you buy through our links.
Read our disclosure page to find out how can you help Windows Report sustain the editorial team. Read more
Setting environment variables on Windows 11 can help you customize your system, run scripts, and configure applications.
In this guide, we will discuss three ways with step-by-step instructions to do that so you can configure your system according to your preferences. But first:
Types of Environment Variables
There are three types of Environment Variables:
- System Environment Variables – The global variables are at the lowest priority, can be accessed by all users & apps on a Windows, and are usually used to define system-wide settings.
- User Environment Variables – With a higher priority, these only apply to the current user & processes running under that account & are set by the user or apps that run under that account.
- Process Environment Variables – With the highest priority, they are temporary and apply to the current process & its child processes, providing runtime information or customization for a program.
How do I set & use Environment Variables on Windows 11?
1. Using the Settings app
- Press Windows + I to open Settings.
- Go to System, then click About.
- Click the Advanced system settings link.
- On the System Properties window, click Environment Variables.
- Next, on the Environment Variables window, you will see two types of variables. Choose an option from either User variables for user or System variables and click New.
- On the following window, type in the Variable name without any spaces, and for Variable Value, click the Browse Directory or Browse File button.
- Select the path and click OK.
2. Using the Command Prompt
- Press the Windows key, type cmd in the search bar, and click Run as administrator.
- To add a temporary variable to your system, use this command after replacing VariableName & Variablevalue with the one you want and hit Enter:
set VariableName = Variablevalue
- The set command is used to define an environment variable within the process for which it is defined and will be deleted once the window is closed.
- To set environment variables permanently, type the following command after replacing the Variablename with the name of the variable & Value with the value you want to set and press Enter:
setx Variablename Value /m
- Now for the path variables, type the following command to list all of them and hit Enter:
echo %PATH%
- Copy & paste the following command to add another variable to the path directory; replace the PATH value with the path you want to add and press Enter:
setx PATH "%PATH%; PATH Value
- Refresh the Environment variable window to see the newly added path.
3. Using the Windows PowerShell
- Press the Windows key, type powershell, and click Run as administrator.
- Type the following command to list of path variables and press Enter: [Environment]::GetEnvironmentVariable(“PATH”)
- Copy & paste the following command to declare a path variable after replacing PATH with the path you want to add and hit Enter:
$Variable_Name = "PATH"
- To add the variable to the Path Variable list, use this command after replacing Folder PATH with the path you declared and press Enter: [Environment]::SetEnvironmentVariable(“Folder PATH”, “$PATH;$Variable_Name”)
- Restart your computer to let the changes take effect.
You can use any of the methods to add a new or missing environment variable to prevent issues like the system could not find the environment option that was entered
- Microsoft wants Windows 10 users to upgrade to Windows 11 or Copilot + PCs
- Windows 11 KB5055627 update makes File Explorer more fluid
- A few keyboard settings are moving from Control Panel to Settings app in Windows 11
- Details of Windows 11 25H2 spotted in the wild; likely to be a smaller update
How do I edit Environment Variables on Windows 11?
1. Using the Settings app
- Press Windows + I to open Settings, then go to System > About >Advanced system settings.
- Click Environment Variables, then select the variable you want to edit and click Edit.
- Make the changes and click OK on all three windows to save the changes.
- Restart the Environment Variable window to see the changes.
2. Using the Registry Editor
- Press Windows + R to open the Run dialog box.
- Type regedit and click OK to open Registry Editor.
- Navigate to this path if you are making changes to User Variables:
Computer\HKEY_CURRENT_USER\Environment
- For System Variables, go to this path:
Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
- Once you have located either of the variables, you can change the name by right-clicking and selecting Rename.
- To edit the value, double-click the variable, change the Value data, and click OK.
- Restart your computer to save the changes.
3. Using the Windows PowerShell
- Open Windows PowerShell with administrator privileges using the same steps mentioned above.
- Type the following command to get the current value of the variable after replacing VARIABLENAME with the variable name and press Enter:
$Env: VARIABLENAME
- Next, to update or edit the value, copy & paste the following command after replacing the VARIABLEANME with the name of the variable & NEWVALUE with the value that you want to add, then hit Enter:
$Env: VARIABLENAME = "NEWVALUE"
- Reboot your PC to save the changes.
How do I get a list of Environment Variables in Windows?
To get a list of environment variables in Windows 11, you can open Command Prompt with administrator rights and type set, and hit Enter.
In Powershell, with admin privileges to get a list of environment variables, copy & paste the following command and hit Enter: [System.Environment]::GetEnvironmentVariables()
If you want to print the environment variables list you got on PowerShell to apply the same settings on another computer, read this guide.
Where are Windows environment variables stored?
You can find the environment variables in Registry Editor. The system variables are found in Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment, wherein the user variables are located at Computer\HKEY_CURRENT_USER\Environment
Setting environment variables on Windows 11 can help you customize your system settings; however, you must always exercise caution when making changes to system variables.
Remember to double-check the variable name & value, and always create a backup of your registry editor before making changes.
Stuck somewhere? Don’t hesitate to mention your queries in the comments section below. We will be happy to assist you.
Srishti Sisodia
Windows Software Expert
Srishti Sisodia is an electronics engineer and writer with a passion for technology. She has extensive experience exploring the latest technological advancements and sharing her insights through informative blogs.
Her diverse interests bring a unique perspective to her work, and she approaches everything with commitment, enthusiasm, and a willingness to learn. That’s why she’s part of Windows Report’s Reviewers team, always willing to share the real-life experience with any software or hardware product. She’s also specialized in Azure, cloud computing, and AI.
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.
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
If you are using Windows PowerShell, list all the environment variables with:
Get-ChildItem Env:
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]%
In Windows PowerShell, use:
echo $Env:[variable_name]
Here, [variable_name]
is the name of the environment variable you want to check.
Set Environment Variable in Windows via GUI
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.
3. Open the Advanced tab and click on the Environment Variables button in the System Properties window.
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.
5. Enter the variable name and value in the New User Variable prompt and click OK.
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"
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
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 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
List all the system environment variables with:
reg query "HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment"
If you want to list a specific variable, use:
reg query HKEY_CURRENT_USEREnvironment /v [variable_name]
or
reg query "HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment" /v [variable_name]
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
or
reg delete "HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment" /v [variable_name] /f
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.
Was this article helpful?
YesNo