If by «system environment variables» you refer specifically to system-wide environment variables, then other answers have already covered this. However, if you want to edit both system-wide and user-specific environment variables then most (if not all) of these answers are inapplicable in general case.
Going through «System» and then “Advanced system settings” -> “Environment Variables” will only work for accounts from Administrators
group, because only such accounts have access to “Advanced system settings”.
If you attempt do that from a regular user account, then trying to access “Advanced system settings” will trigger an UAC prompt asking you for administrator password. If you enter the password, “Advanced system settings” will successfully open, but any user-specific changes you make there will apply to the corresponding administrator’s account (!), not to your original user’s account.
In order to solve this problem (i.e. in order to give regular users the opportunity to edit their own environment variables) Windows provides another way to access the “Environment Variables” dialog.
Open Control Panel. Open User Accounts applet. On the left-hand side of that applet you will see a link that says Change my environment variables. Click that link, and it will take you to the same “Environment Variables” dialog for your user’s environment variables.
If your user has administrator rights, you will be able to edit both sections of that dialog: user-specific environment variables (upper section) and system-wide environment variables (lower section). If you don’t have administrator rights, you will only be able to edit the upper section: your own user-specific environment variables.
This is the proper way to edit environment variables in all post-UAC versions of Windows, not what is suggested in the majority of the answers above.
Unfortunately, Windows 10 November update (version 1511) destroyed this functionality. The Change my environment variables link no longer works. It is there, but it is dead. So for the post-November version of Windows 10 the correct answer is: it is generally impossible to edit user-specific environment variables in version 1511 of Windows 10 from regular user accounts. Microsoft has destroyed Windows 10 with this update and Windows 10 is now unusable. It will remain the case until they fix these ridiculous bugs in 1511 version of the OS.
For the time being one workaround for non-administrative accounts is to, well, add your user account to Administrators
group, logout, log back in, edit the variables using «System» -> “Advanced system settings” method, and then take away administrative rights again…
An alternative workaround is to use PowerShell features as described here
https://technet.microsoft.com/en-us/library/ff730964.aspx
Windows 10 Anniversary Update (version 1607) released August 2, 2016 finally fixed this bug.
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.
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.
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.
If by «system environment variables» you refer specifically to system-wide environment variables, then other answers have already covered this. However, if you want to edit both system-wide and user-specific environment variables then most (if not all) of these answers are inapplicable in general case.
Going through «System» and then “Advanced system settings” -> “Environment Variables” will only work for accounts from Administrators
group, because only such accounts have access to “Advanced system settings”.
If you attempt do that from a regular user account, then trying to access “Advanced system settings” will trigger an UAC prompt asking you for administrator password. If you enter the password, “Advanced system settings” will successfully open, but any user-specific changes you make there will apply to the corresponding administrator’s account (!), not to your original user’s account.
In order to solve this problem (i.e. in order to give regular users the opportunity to edit their own environment variables) Windows provides another way to access the “Environment Variables” dialog.
Open Control Panel. Open User Accounts applet. On the left-hand side of that applet you will see a link that says Change my environment variables. Click that link, and it will take you to the same “Environment Variables” dialog for your user’s environment variables.
If your user has administrator rights, you will be able to edit both sections of that dialog: user-specific environment variables (upper section) and system-wide environment variables (lower section). If you don’t have administrator rights, you will only be able to edit the upper section: your own user-specific environment variables.
This is the proper way to edit environment variables in all post-UAC versions of Windows, not what is suggested in the majority of the answers above.
Unfortunately, Windows 10 November update (version 1511) destroyed this functionality. The Change my environment variables link no longer works. It is there, but it is dead. So for the post-November version of Windows 10 the correct answer is: it is generally impossible to edit user-specific environment variables in version 1511 of Windows 10 from regular user accounts. Microsoft has destroyed Windows 10 with this update and Windows 10 is now unusable. It will remain the case until they fix these ridiculous bugs in 1511 version of the OS.
For the time being one workaround for non-administrative accounts is to, well, add your user account to Administrators
group, logout, log back in, edit the variables using «System» -> “Advanced system settings” method, and then take away administrative rights again…
An alternative workaround is to use PowerShell features as described here
https://technet.microsoft.com/en-us/library/ff730964.aspx
Windows 10 Anniversary Update (version 1607) released August 2, 2016 finally fixed this bug.
Настройка переменных среды 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
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
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.