Настройка переменных среды 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
Environment variables is not a new term in context to Windows 10. People have known them for years, as they are available in Windows series since older days of Windows XP. But still the fact is that many newbies to Windows aren’t aware of them. In this article, we’ll let you know about these variables and show the way to edit or modify them.
Basically, environment variables are strings that contain information such as drive, path, or file name. They control the behavior of various programs. For example, %windir% is an environment variable which when run in Command Prompt, opens the Windows folder under system root drive such as C:\Windows. There are two kind of environment variables a Windows operating system have. The first category is of user environment variables, which the user(s) and/or administrator(s), both can modify anytime. Second class is of system environment variables, which only system admin(s) can modify.
Keep in mind that the user environment variables are different for each user of a particular computer. The variables include any that are set by the user, as well as any variables defined by programs, such as the path to the location of the program files. While for system environment variables, administrators can change or add environment variables that apply to the system, and thus to all system users. During installation, Windows Setup configures the default system variables, such as the path to the Windows files.
Page Contents
How To Change User And System Environment Variables In Windows 10
1. Open administrative or elevated Windows PowerShell. For this search in Windows by term windows powershell, pick Windows PowerShell from search results, right click on it and select Run as administrator.
Recommended : Use Windows PowerShell to find Windows Experience Index on Windows 10
2. Next, in the Windows PowerShell window, type following cmdlet and press Enter key:
Get-ChildItem Env:
This cmdlet output will show you the list all environment variables available on your system. You can also edit or modify the variables in Windows PowerShell itself, but this would be bit technical. So for the sake of readers, I’ll show you much familiar way to edit these variables.
Registry Disclaimer: The further steps will involve registry manipulation. Making mistakes while manipulating registry could affect your system adversely. So be careful while editing registry entries and create a System Restore point first.
3. Press + R and put regedit in Run dialog box to open Registry Editor (if you’re not familiar with Registry Editor, then click here). Click OK.
4. In the left pane of Registry Editor, navigate to following registry key:
HKEY_CURRENT_USER\Environment
5. At this registry location as shown above, you can see there are two user environment variables by default. To add a new environment variable, right click on blank space in the right pane, select New -> Expandable String Value. Change the string name so created from New Value #1 to whatever you want to say the variable. Now, for existing variables, double click on the variable string to add or modify its Value data:
Put you desired Value data in Edit String window and click OK. In this way, you can add or modify user environment variables.
6. In order to modify system environment variables, navigate to following registry key and perform the registry manipulation as described in previous step:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
We’ve highlighted some important variables in the screenshot above. So in this way, you can add or modify system environment variables. You may need to restart your system, to make your changes effective.
List of environment variables in Windows 10
For your convenience, here is the complete list of environment variables in Windows 10.
ENVIRONMENT VARIABLES |
VALUES (items in italic – variables) |
%ALLUSERSPROFILE% | C:\ProgramData |
%APPDATA% | C:\Users\(user-name)\AppData\Roaming |
%CD% | Current directory full path |
%CMDCMDLINE% | Returns exact command line used to start current cmd.exe session. |
%CMDEXTVERSION% | Number of current command processor extensions. |
%CommonProgramFiles% | C:\Program Files\Common Files |
%CommonProgramFiles(x86)% | C:\Program Files (x86)\Common Files |
%CommonProgramW6432% | C:\Program Files\Common Files |
%COMPUTERNAME% | Technoyl-PC |
%COMSPEC% | C:\Windows\System32\cmd.exe |
%DATE% | Current date in format determined by Date command |
%ERRORLEVEL% | Number defining exit status of previous command or program |
%HOMEDRIVE% | C: |
%HOMEPATH% | C:\Users\(user-name) |
%LOCALAPPDATA% | C:\Users\(user-name)\AppData\Local |
%LOGONSERVER% | \\MicrosoftAccount |
%NUMBER_OF_PROCESSORS% | 1 |
%OS% | Windows_NT |
%PATH% | C:\WINDOWS
C:\WINDOWS\system32 C:\WINDOWS\System32\Wbem C:\WINDOWS\System32\WindowsPowerShell\v1.0 |
%PATHEXT% | COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC |
%PROCESSOR_ARCHITECTURE% | x86 |
%PROCESSOR_IDENTIFIER% | x86 Family 6 Model 69 Stepping 1, GenuineIntel |
%PROCESSOR_LEVEL% | 6 |
%PROCESSOR_REVISION% | 4501 |
%ProgramData% | C:\ProgramData |
%ProgramFiles% | C:\Program Files |
%ProgramFiles(x86)% | C:\Program Files (x86) |
%ProgramW6432% | C:\Program Files |
%PROMPT% | Code for current command prompt format. Code is usually $P$G |
%PSModulePath% | C:\Windows\system32\WindowsPowerShell\v1.0\Modules\ |
%PUBLIC% | C:\Users\Public |
%RANDOM% | To get random number between 0 and 32767 |
%SessionName% | When logging on directly to machine, returns “Console”.
When client connects via terminal server session, is combination of connection name, followed by pound symbol {#} and session number. |
%SystemDrive% | C: |
%SystemRoot% | C:\Windows |
%TEMP% | C:\Users\(user-name)\AppData\Local\Temp |
%TIME% | Current time in format determined by Time command |
%TMP% | C:\Users\(user-name)\AppData\Local\Temp |
%USERDOMAIN% | Technoyl-PC |
%USERDOMAIN_ROAMINGPROFILE% | Technoyl-PC |
%USERNAME% | (user-name) |
%USERPROFILE% | C:\Users\(user-name) |
%WINDIR% | C:\Windows |
Hope you find the article useful! Also learn how to scan your Windows 10 using Windows PowerShell.
RELATED ARTICLES
Способ 1: Переменные среды
К добавлению путей в переменную окружения Path часто прибегают, когда нужно обеспечить возможность быстрого запуска портативных программ из диалогового окошка «Выполнить». Отредактировать переменную Path можно средствами самой Windows.
- Нажатием клавиш Win + R вызовите диалоговое окошко быстрого запуска и выполните в нем команду
systempropertiesadvanced
, чтобы открыть дополнительные свойства системы. - Нажмите кнопку «Переменные среды», чтобы открыть одноименную оснастку.
- В Windows доступны две переменные Path: пользователя и системы. Если вносимые изменения должны затронуть всех пользователей, необходимо выбрать системную переменную. Выделите последнюю мышкой и нажмите кнопку «Изменить».
- Откроется окошко со списком уже существующих путей. Нажмите в нем кнопку «Изменить текст».
- Нажмите «OK» в окошке с предупреждением.
- Откроется окно редактирования переменной. Скопируйте свой путь и вставьте его в конец уже имеющегося значения в поле «Значение переменной», отделив его точкой с запятой. Перед точкой с запятой также следует добавить слеш, если таковой отсутствует.
- Сохраните настройки и перезагрузите компьютер.
После этого обращаться к файлам и каталогам по добавленному пути можно будет напрямую, используя их имена.
Способ 2: Редактирование реестра
Пользователи, имеющие навыки работы с реестром, могут добавить свой путь в переменную Path путем редактирования соответствующих параметров в реестре.
- Откройте «Редактор реестра» командой
regedit
в окошке Win + R. - Перейдите к ветке
HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
, если нужно отредактировать системную переменную, илиHKCU\Environment
, если целью является пользовательская переменная. В правой колонке отыщите строковый параметр с названием «Path» и кликните по нему дважды, чтобы открыть окошко редактирования значения. - Добавьте в конец текущего значения свой путь, отделив его точкой с запятой. Как и в предыдущем способе, перед разделителем необходимо добавить слеш.
- Сохраните настройки, закройте «Редактор реестра» и перезагрузите компьютер.
Способ 3: Сторонние программы
Для работы с переменными Windows существуют также специальные программы-редакторы. Примером такой программы является Rapid Environment Editor. Приложение поддерживает просмотр переменных окружения, выбор значений переменных из дерева каталогов, проверку корректности перечисленных в переменных путей и имен файлов, экспорт переменных и их значений в reg-файл.
Скачать Rapid Environment Editor с официального сайта
- Скачайте архив с программой с сайта разработчика, распакуйте и запустите исполняемый файл rapidee.exe от имени администратора. Выберите на панели инструментов, если нужно, русский язык интерфейса.
- Приложение имеет двухпанельный интерфейс: на левой панели расположен список системных переменных, в правой колонке перечислены пользовательские переменные окружения. Скопируйте в буфер обмена добавляемый путь, нажмите правой кнопкой мыши по переменной Path и выберите в контекстном меню опцию «Добавить значение».
- Вставьте путь в появившуюся форму и нажмите клавишу ввода.
- Сохраните результат редактирования, выбрав в главном меню «Файл» опцию «Сохранить».
При необходимости новый элемент (путь) может быть вставлен в начало, середину или конец текущего значения переменной. Перемещать его в Rapid Environment Editor можно простым перетаскиванием.
Существуют также и другие способы добавления путей в переменную Path, но они гораздо менее удобны. Например, переменная пути может быть отредактирована в «Командной строке» или консоли «PowerShell».
Наша группа в 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 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