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.
Настройка переменных среды 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
To make the environment variable accessible globally you need to set it in the registry. As you’ve realised by just using:
set NEWVAR=SOMETHING
you are just setting it in the current process space.
According to this page you can use the setx
command:
setx NEWVAR SOMETHING
setx
is built into Windows 7, but for older versions may only be available if you install the Windows Resource Kit
nhinkle
37.2k36 gold badges140 silver badges177 bronze badges
answered Dec 6, 2009 at 21:58
ChrisFChrisF
41.3k17 gold badges101 silver badges154 bronze badges
5
We can also use «setx var variable /M» to set the var to system environment variable level instead of user level.
Note: This command should be run as administrator.
music2myear
40.7k44 gold badges86 silver badges127 bronze badges
answered Aug 26, 2014 at 10:37
Minh ChauMinh Chau
5014 silver badges2 bronze badges
You can use setx env var [/M]
as mentioned above.
If it doesn’t take effect you can use refreshenv
to refresh environment variables. You don’t have to restart your computer, explorer.exe or your command prompt to do that.
Edit: apparantly refreshenv doesn’t come naturally with Windows, so here’s the source: https://pastebin.com/1fJqA0pT
Save as RefreshEnv.cmd and place it in a folder that’s included in your PATH environment variables
answered Nov 13, 2018 at 19:42
DFSFOTDFSFOT
2112 silver badges5 bronze badges
1
System variables can be set through CMD and registry
For ex. reg query «HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment» /v PATH
All the commonly used CMD codes and system variables are given here: Set Windows system environment variables using CMD.
Open CMD and type Set
You will get all the values of system variable.
Type set java to know the path details of java installed on your window OS.
answered Mar 9, 2017 at 5:06
2
I want to add that if you are using the /s parameter with setx in order to set environment variables on a remote computer, the «Remote Registry» service needs to be running on the target machine or else you will receive a «ERROR: The specified operation could not be completed.»
(I have asked Microsoft to update their TechNet article on setx to include this information.)
answered May 18, 2017 at 19:35
Tim BailenTim Bailen
911 silver badge3 bronze badges
You must log in to answer this question.
Not the answer you’re looking for? Browse other questions tagged
.
Not the answer you’re looking for? Browse other questions tagged
.
Windows Command Line – Set Environment Variable
The windows command line or text interface is a kind of user interface that can be controlled by passing commands in the form of prompts instead of using a mouse. Command-line is different from GUI OS, i.e., Graphical User Interface Operating System. It only needs a keyboard to control and navigate by passing the commands instead of a mouse.
For example, to open the windows folder in the windows command line, we use “C:\Windows”.
However, using the command line requires one to remember lots of commands. However, it is very useful which should not be ignored. Command-line allows a user to perform all the tasks that they can perform on a GUI OS. And sometimes, there are many tasks that we can accomplish even quicker than GUI OS, and they are very easy to automate as well.
For example, if a person is asked to rename 50 files in a folder at a time. So, setting an environment variable with GUI can be very time-consuming but with the help of the windows command line, this can be done in seconds by passing a single command using a batch file or other scripts.
What is an Environment Variable?
An environment variable is a dynamic object that contains an editable value. It can be used by more than one software program in windows. The role of environment variables is to let the programs know which file directories to install, the location of temporary files, and the user profile settings. These are named environment variables because they shape the environment of the essential programs to run a computer.
How to set environment variables?
To set up an environment variable, the running system should have windows 10 OS. The user account should have admin privilege. It should also have access to Command Prompt or Windows PowerShell. Users can set up environment variables in two ways –
1. Via GUI
To set up environment variable using GUI, the user should follow the following steps-
- With the help of windows run, open System Properties.
- Then select the Advanced option in the top menu and set Environment Variables.
- The Environment Variables have two sections, user-specific and system-wide. So, to add a new environment variable, press the new button. Then, the user can add the variable according to their choice.
2. Via Command Prompt
- To set an environment variable with the help of a command prompt, use ‘setx’.
- For example – setx [variable_name] “[variable_value]. Here, the variable name can be assigned the name of the variable you want to keep and value, the value you want to assign the variable.
- Furthermore, if a user wants to add a system-wide environment variable, then use – setx [variable_name] “[variable_value]” /M.
Other useful articles:
- Basic Windows CMD commands
- Cool CMD Commands Tips and Tricks
- Best CMD Commands for Hacking
- CMD Commands for Wireless Network Speed
- Useful Keyboard Shortcuts for CMD
- What Info about My Laptop Can I Check with CMD and How?
- Getting Started with CMD Windows
- TOP-12 Command-Line Interview Questions (Basic)
- Command-Line Interview Questions (Advanced)
- CMD Commands to Repair Windows
- CMD Commands to Speed Up Computer
- CMD Commands for MAC OS
- How Does the Command Line Work?
- MS-Dos Interview Questions in 2021
- Windows OS Versions and History
- Recent Windows Versions Compared
- Basic Windows Prompt Commands for Every Day
- Windows Command Line Cheat Sheet For Everyone
- Windows Command Line Restart
- Windows Command Line for Loop
- Windows Command — Change Directory
- Windows Command — Delete Directory
- Windows Command Line – Set Environment Variable
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.