Different programs and processes require different environments to run. On a single machine, Windows needs to make sure that all programs and processes can access the environments they need.
To do this, Windows needs to know the kind of environment every program requires to work. Windows must store this information somewhere for easier retrieval. Environment variables make that possible.
Environment variables are, in short, data storing mechanisms.
Let’s dig a little deeper to see how environment variables work and how you can create, edit, and delete them effectively.
What Are Environment Variables in Windows 10?
Environment variables are dynamic variables that store data related to creating different environments for different programs and processes.
To understand them better, let us take the example of a program that needs to use a built-in Windows tool to run.
For the program to use the tool, the program needs to know the tool’s location to access it. The program also needs to find out if it has permission to use the tool or not. Similarly, there are things that a program needs to know before it can use the tool.
So, a program can access all of this information by asking Windows. Windows then looks up environment variables (EVs) for this data and creates an environment in which that program can run.
In other words, EVs store data that is accessible to every program and process running on the system across all users. The data these variables store helps the programs run in the environment they were designed for.
Some of the most important EVs on Windows include PATH, HOMEPATH, and USERNAME. All of these variables contain values that any user and process of the system can access at any time. For instance, the USERNAME environment variable contains the name of the current user. Windows can look up this variable whenever it needs to find out the name of the current user.
How to Set Environment Variables in Windows 10?
First things first, if you want to set system-wide EVs, you need to have administrative privileges. So, if you are not the admin, inform your system administrator and ask for their help.
Now that you have admin privileges:
- Type Advanced system settings in the Start menu search box and select the Best match.
- In the System Properties box, click on Environment Variables to open the Environment Variables panel.
The EVs panel lists two types of variables depending upon your need. If you want to change EVs for the current user only and don’t want the changes to reflect system-wide, you will change User variables.
On the contrary, if you want system-wide changes, you will change System variables.
Let’s say you’ve just installed Java and want to add the java path to the EVs. To do this:
- Click on New under the User/System variables. This will open up the New User Variable box.
- Enter JAVA_HOME in the Variable name field and browse to the directory where you’ve installed Java to populate the path in Variable value.
Pressing OK will add the JAVA_HOME variable to the PATH variable.
How to Edit Environment Variables
To edit different environment variables, select any variable from the list. Then, press Edit. This will open up the Edit environment variable panel. Here you can create, delete, and edit variables.
From the list of variables, select the one that you want to modify and click on Edit. Afterward, you can change the variable value to anything you like.
You can also delete the variables in a similar fashion.
What Is the Windows PATH Variable and How Can I Change it?
In simple terms, the PATH variable is an address book of programs and commands on your computer. Whenever you have a new program on your computer that you want to run from the command line interface, you must specify its address in the PATH variable.
A thing to remember here, not all programs are in the PATH environment variable. Only the programs that are meant to be used from the command line interface appear in the PATH variable. So, programs intended to be used from a Graphical User Interface don’t have their addresses in the PATH variable.
The way the process works involves Windows looking up the address for a certain command. Whenever you issue a command on a command line, Windows first searches the current directory for the command. If the OS can’t find it in the current directory, it looks up the PATH variable to find the address.
To enter an address in the PATH variable, the process is the same as before. Open up the Environment Variable box, select the PATH variable, and click on Edit.
In the Edit box, you can add, remove, and edit directories.
One final thing to remember, the PATH variable is not the same for every user on a system. So different users can list different directories without changing the variable for every user. So, if you want a tool to be available for every user, you have to edit the PATH variable under the System Variables.
Environment Variables in Windows 10 Store Data that Programs Need to Work
Programs need data to work. To make sure that data is available efficiently, Windows stores this data in global variables that all programs can access. These global variables are Environment Variables.
You can add, edit, and remove Environment Variables inside the Advanced System Settings panel.
Furthermore, if you have more than one user on a machine, user Environment Variables will be different for each user. For instance, one user may have listed a command under the PATH variable that won’t be available for other users.
On the other hand, system EVs are available for all users. These variables require admin privileges to edit or delete.
In short, EVs are Windows’ way to store important data. So, be sure you know what you are doing before modifying them.
Настройка переменных среды 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
- Переменные PATH и PATHEXT
- Создание переменных среды
- Заключение
- Вопросы и ответы: 6
Переменная среды (переменная окружения) – это короткая ссылка на какой-либо объект в системе. С помощью таких сокращений, например, можно создавать универсальные пути для приложений, которые будут работать на любых ПК, независимо от имен пользователей и других параметров.
Переменные среды Windows
Получить информацию о существующих переменных можно в свойствах системы. Для этого кликаем по ярлыку Компьютера на рабочем столе правой кнопкой мыши и выбираем соответствующий пункт.
Переходим в «Дополнительные параметры».
В открывшемся окне с вкладкой «Дополнительно» нажимаем кнопку, указанную на скриншоте ниже.
Здесь мы видим два блока. Первый содержит пользовательские переменные, а второй системные.
Если требуется просмотреть весь перечень, запускаем «Командную строку» от имени администратора и выполняем команду (вводим и нажимаем ENTER).
set > %homepath%\desktop\set.txt
Подробнее: Как открыть «Командную строку» в Windows 10
На рабочем столе появится файл с названием «set.txt», в котором будут указаны все переменные окружения, имеющиеся в системе.
Все их можно использовать в консоли или скриптах для запуска программ или поиска объектов, заключив имя в знаки процента. Например, в команде выше вместо пути
C:\Users\Имя_пользователя
мы использовали
%homepath%
Примечание: регистр при написании переменных не важен. Path=path=PATH
Переменные PATH и PATHEXT
Если с обычными переменными все понятно (одна ссылка – одно значение), то эти две стоят особняком. При детальном рассмотрении видно, что они ссылаются сразу на несколько объектов. Давайте разберемся, как это работает.
«PATH» позволяет запускать исполняемые файлы и скрипты, «лежащие» в определенных каталогах, без указания их точного местоположения. Например, если ввести в «Командную строку»
explorer.exe
система осуществит поиск по папкам, указанным в значении переменной, найдет и запустит соответствующую программу. Этим можно воспользоваться в своих целях двумя способами:
- Поместить необходимый файл в одну из указанных директорий. Полный список можно получить, выделив переменную и нажав «Изменить».
- Создать свою папку в любом месте и прописать путь к ней. Для этого (после создания директории на диске) жмем «Создать», вводим адрес и ОК.
%SYSTEMROOT% определяет путь до папки «Windows» независимо от буквы диска.
Затем нажимаем ОК в окнах «Переменные среды» и «Свойства системы».
Для применения настроек, возможно, придется перезапустить «Проводник». Сделать это быстро можно так:
Открываем «Командную строку» и пишем команду
taskkill /F /IM explorer.exe
Все папки и «Панель задач» исчезнут. Далее снова запускаем «Проводник».
explorer
Еще один момент: если вы работали с «Командной строкой», ее также следует перезапустить, то есть консоль не будет «знать», что настройки изменились. Это же касается и фреймворков, в которых вы отлаживаете свой код. Также можно перезагрузить компьютер или выйти и снова зайти в систему.
Теперь все файлы, помещенные в «C:\Script» можно будет открывать (запускать), введя только их название.
«PATHEXT», в свою очередь, дает возможность не указывать даже расширение файла, если оно прописано в ее значениях.
Принцип работы следующий: система перебирает расширения по очереди, пока не будет найден соответствующий объект, причем делает это в директориях, указанных в «PATH».
Создание переменных среды
Создаются переменные просто:
- Нажимаем кнопку «Создать». Сделать это можно как в пользовательском разделе, так и в системном.
- Вводим имя, например, «desktop». Обратите внимание на то, чтобы такое название еще не было использовано (просмотрите списки).
- В поле «Значение» указываем путь до папки «Рабочий стол».
C:\Users\Имя_пользователя\Desktop
- Нажимаем ОК. Повторяем это действие во всех открытых окнах (см. выше).
- Перезапускаем «Проводник» и консоль или целиком систему.
- Готово, новая переменная создана, увидеть ее можно в соответствующем списке.
Для примера переделаем команду, которую мы использовали для получения списка (самая первая в статье). Теперь нам вместо
set > %homepath%\desktop\set.txt
потребуется ввести только
set > %desktop%\set.txt
Заключение
Использование переменных окружения позволяет значительно сэкономить время при написании скриптов или взаимодействии с системной консолью. Еще одним плюсом является оптимизация создаваемого кода. Имейте в виду, что созданные вами переменные отсутствуют на других компьютерах, и сценарии (скрипты, приложения) с их использованием работать не будут, поэтому перед тем, как передавать файлы другому пользователю, необходимо уведомить его об этом и предложить создать соответствующий элемент в своей системе.
Наша группа в TelegramПолезные советы и помощь
System and User Environment Variables have 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 answered shortly 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 of 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 provides 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, the environment provides values that help other programs in obtaining some crucial information about the system. 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.
Read: How to use Environment Variable Editor in PowerToys?
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 you are very sure about your actions. To open the ‘Environment Variables’ Window, follow these steps:
- Right-click ‘This PC’ icon and select ‘Properties’.
- Now in this window, select ‘Advanced System Settings’ from the left part.
- Hit the last button saying ‘Environment Variables’ to open our destined window.
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.
Read: Environment Variables not working in Windows 11
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 set up 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.
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 the 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 to make 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.
В Windows 10 переменные среды — это предварительно определенные имена, представляющие путь к определенным местам в операционной системе, например к диску, конкретному файлу или папке.
Переменные среды могут быть полезны в ряде сценариев, они особенно полезны, если вы являетесь специалистом по ИТ или чините чужой компьютер, поскольку вы можете быстро перемещаться в определенные места, даже не зная имени пользователя или полного пути к системной папке.
Например, вместо перехода по следующему пути C:\Users\<UserName>\AppData\Roaming можно открыть команду «Выполнить» (клавиша Windows + R), ввести %APPDATA% и нажать клавишу Enter для доступа к тому же пути. Или вы можете использовать переменную %HOMEPATH% для доступа к местоположению папок по умолчанию для текущего пользователя — где операционная система хранит папки рабочего стола, документов, загрузок, OneDrive и т. Д.
Переменные среды по умолчанию в Windows 10
VARIABLE | WINDOWS 10 |
---|---|
%ALLUSERSPROFILE% | C:\ProgramData |
%APPDATA% | C:\Users\{имя пользователя}\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\{имя пользователя} |
%LOCALAPPDATA% | C:\Users\{имя пользователя}\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\{имя пользователя}\AppData\Local\Temp |
%TMP% | C:\Users\{имя пользователя}\AppData\Local\Temp |
%USERDOMAIN% | Пользовательский домен, связанный с текущим пользователем. |
%USERDOMAIN_ROAMINGPROFILE% | Пользовательский домен, связанный с перемещаемым профилем. |
%USERNAME% | {имя пользователя} |
%USERPROFILE% | C:\Users\{имя пользователя} |
%WINDIR% | C:\Windows |
%PUBLIC% | C:\Users\Public |
%PSModulePath% | %SystemRoot%\system32\WindowsPowerShell\v1.0\Modules\ |
%OneDrive% | C:\Users\{имя пользователя}\OneDrive |
%DriverData% | C:\Windows\System32\Drivers\DriverData |
%CD% | Выводит текущий путь к каталогу. (Командная строка.) |
%CMDCMDLINE% | Выводит командную строку, используемую для запуска текущего сеанса командной строки. (Командная строка.) |
%CMDEXTVERSION% | Выводит количество текущих расширений командного процессора. (Командная строка. |
%COMPUTERNAME% | Выводит имя системы. |
%DATE% | Выводит текущую дату. (Командная строка.) |
%TIME% | Время выхода. (Командная строка.) |
%ERRORLEVEL% | Выводит число определяющих статус выхода предыдущей команды. (Командная строка.) |
%PROCESSOR_IDENTIFIER% | Идентификатор процессора |
%PROCESSOR_LEVEL% | Outputs processor level. |
%PROCESSOR_REVISION% | Вывод ревизии процессора. |
%NUMBER_OF_PROCESSORS% | Выводит количество физических и виртуальных ядер. |
%RANDOM% | Выводит случайное число от 0 до 32767. |
%OS% | Windows_NT |
Хотя вы можете использовать переменные среды для быстрого доступа к определенным местам в Windows 10, вы, как правило, будете использовать эти переменные при создании сценария или приложения.
Помните, что некоторые из упомянутых переменных не зависят от местоположения, в том числе % COMPUTERNAME%, %PATHEXT%, %PROMPT%, %USERDOMAIN%, %USERNAME%.
Хотя это руководство ориентировано на Windows 10, важно отметить, что эти переменные также будут работать в Windows 11, Windows 8.x, Windows 7 и Windows Vista.