Настройка переменных среды 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Полезные советы и помощь
Windows 10 supports a number of legacy features from older versions of the operating system. One of those legacy features is the environment variable. Environment variables offer a useful way to control the way Windows operates with an extremely small footprint in terms of memory usage.
For example, one common environment variable is called PATH, which is simply an ordered text string containing a list of directories that Windows should look in when an executable file is called. The PATH environment variable allows users to quickly launch programs without having to know where those programs live on the hard drive.
Setting environment variables is very useful and, fortunately, very simple. In this article, we’ll go over how to find and set your environment variables in Windows 10.
- Once logged in to Windows, right-click the Windows button in the lower-left corner of your screen and click System from the Power User Task Menu that’s displayed on the screen.
- Under the System menu, you need to click the Advanced System Settings.
- If you can’t find Advanced System Settings there, type “advanced system settings” into the search box and hit return to bring it up.
- Once Advanced System Settings is open, click on the Advanced tab, then look on the bottom-right side for the Environment Variables.
- Next, to create a new environment variable, click New. You might need to make a System variable depending upon what you’re doing.
- A dialog box will pop up, allowing you to enter a new variable name and to set its initial value:
- New adds a new environment variable.
- Edit lets you edit whatever environment variable you have selected.
- Delete lets you delete the selected environment variable.
- Save any changes that you make by clicking OK.
How to Find the PATH Variable in Windows 10
- Under the Environment Variables window, choose or highlight the PATH variable in the System Variables section shown in the window.
- After highlighting the PATH variable from System Variables, click the Edit button.
- You can add or modify the path lines with the directories you want your computer to look in for executable files.
- You will find that each different directory is separated with a semicolon, for example:
C:Program Files;C:Winnt;C:WinntSystem32
- You will find that each different directory is separated with a semicolon, for example:
- There are other environment variables in the System Variables section that you can examine by clicking Edit.
- Likewise, there are different environment variables, such as PATH, HOME, USER PROFILE, HOME and APP DATA, TERM, PS1, MAIL, TEMP, and so on. These Windows environment variables are very useful and can be used in scripts as well as on the command line.
- Once finished, you can test your changes by opening a new PowerShell window and entering the following:
$env:PATH
Frequently Asked Questions
Here is some more information about Environment Variables for you:
How Do I Find Environment Variables in Windows 10?
To find environment variables in Windows 10, you can follow the steps described above to find the environment variable information tucked away inside the system’s advanced settings.
Alternatively, if you just need to see what the variables are but don’t need to change them, you can simply open a command-line interface by hitting Ctrl +Esc and typing “cmd” in the command box, then type “set” in the command window. This prints out all the environment variables that are set on your system.
Why Can’t I Edit the Environment Variables?
There are several reasons that you may not be able to set these variables.
1. The first of your problems could be that you don’t have Admin rights. To set or edit this function, you must be the Administrator of the system.
2. If you are the Admin, yet the edit function is greyed out, try accessing the Environment Variables by accessing the Control Panel from the Start menu. Click on Advanced System Settings, then click Environment Variables.
Final Thoughts
Windows 10 environment variables make it incredibly easy to take control of your Windows device and make it run more efficiently. To find and set environment variables in Windows 10, follow the simple steps laid out in this article to get started.
Disclaimer: Some pages on this site may include an affiliate link. This does not effect our editorial in any way.
Send To Someone
Missing Device
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.
UPDATED 8/1/2023: On Windows 11 (and 10), environment variables are predefined names representing the path to certain locations within the operating system, such as a drive or a particular file or folder.
Environment variables can be helpful in many scenarios, but they’re particularly useful if you’re a network administrator or troubleshooting a device, as you can quickly navigate to certain locations without even knowing the username or full path to a system folder.
For example, instead of browsing a path like “C:\Users\UserName\AppData\Roaming,” you can open the “Run” command, type this variable “%APPDATA%,” and press Enter to access the same path. Or you can use the “%HOMEPATH%” variable to access the current user’s default profile folder location (where the system stores the folders for Desktop, Documents, Downloads, and OneDrive).
This guide will teach you the list of the most common environment variables you can use on Windows 11 (and on Windows 10).
Variable | Windows 10 and Windows 11 |
---|---|
%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 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 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 number from 0 through 32767. |
%OS% | Windows_NT |
Although you can use environment variables to access certain locations within Windows 11 quickly, you’ll typically use these variables when building a script or an application.
Keep in mind that some of the variables mentioned are not location-specific, including %COMPUTERNAME%
, %PATHEXT%
, %PROMPT%
, %USERDOMAIN%
, %USERNAME%
.
You can always view all the environment variables available on your device using the Get-ChildItem Env: | Sort Name
PowerShell command.
While this guide is focused on Windows 10 and 11, it’s important to note that these variables will also work on Windows 8.1, Windows 7, and Windows Vista.
Mauro Huculak is a
Windows How-To Expert and founder of
Pureinfotech
(est. 2010). With over 21 years as a technology writer and IT Specialist,
Mauro specializes in Windows, software, and cross-platform systems such as Linux, Android, and macOS.
Certifications:
Microsoft Certified Solutions Associate (MCSA),
Cisco Certified Network Professional (CCNP),
VMware Certified Professional (VCP),
and
CompTIA A+ and Network+.
Mauro is a recognized Microsoft MVP and has also been a long-time contributor to Windows Central.
You can follow him on
YouTube,
Threads,
BlueSky,
X (Twitter),
LinkedIn and
About.me.
Email him at [email protected].