Переменные среды в windows 10 pro

Переменные среды Windows 11 и Windows 10Настройка переменных среды 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

Прежде чем приступать, учтите: изменение системных переменных среды по умолчанию может привести к проблемам в работе системы, не удаляйте уже имеющиеся переменные среды. Возможно, имеет смысл создать точку восстановления системы, если вы не уверены в своих действиях.

  1. Чтобы открыть переменные среды Windows вы можете использовать поиск в панели задач (начните вводить «Переменных» и откройте пункт «Изменение системных переменных среды») или нажать клавиши Win+R на клавиатуре, ввести sysdm.cpl и нажать Enter. Открыть изменение переменных среды в Windows
  2. На вкладке «Дополнительно» нажмите кнопку «Переменные среды…» Переменные среды в параметрах системы Windows
  3. В разделе «Переменные среды пользователя» (если требуется изменение только для текущего пользователя) или «Системные переменные» выберите переменную, которую нужно изменить и нажмите «Изменить» (обычно требуется именно это), либо, если необходимо создать новую переменную — нажмите кнопку «Создать». В моем примере — добавляем свои пути в системную переменную Path (выбираем эту переменную и нажимаем «Изменить»). Создание и изменение переменных среды Windows
  4. Для добавления нового значения (пути) в системную переменную в следующем окне можно нажать кнопку «Создать», либо просто дважды кликнуть по первой пустой строке, затем — ввести нужный путь к папке, содержащей нужные нам исполняемые файлы. Изменение переменно PATH
  5. Также вы можете использовать кнопку «Изменить текст», в этом случае окно изменения системной переменной откроется в ином виде: имя переменной, а ниже — её значение. В случае указания путей значение будет представлять собой все пути, хранящиеся в переменной, разделенные знаком «точка с запятой». Изменение имени и значения системной переменной среды
  6. При создании новой переменной среды окно будет тем же, что и в 5-м шаге: необходимо будет указать имя системной переменной в верхнем поле, а её значение — в нижнем.

После создания или изменения переменной среды и сохранения сделанных настроек, переменная или обновленные значения сразу становятся доступны для текущего пользователя или в системе в целом в зависимости от того, какие именно переменные редактировались или создавались. Также есть методы добавления переменных среды в командной строке или PowerShell, подробнее в статье: Как добавить путь в переменную среды PATH

Всем привет! Переменные среды (Environment Variables) в Windows 10 и Windows 11 – это специальные переменные, которые можно свободно использовать в командной строке, скриптах или в некоторых командах во встроенных приложениях (как например, в окне «Выполнить»). Очень полезная вещь для тех людей, которые постоянно пользуются консолью или скриптами. Например, вам необязательно постоянно вручную указывать полный путь к папке, которая находится глубоко на диске – достаточно просто прописать переменную.

Сегодня в статье я расскажу, где находятся системные переменные среды (Environment Variables) Windows, как с ними работать и создавать. Если возникнут какие-то дополнительные вопросы – пишите в комментариях.

Содержание

  1. Где хранятся существующие переменные
  2. PATH и PATHEXT
  3. Создание переменной
  4. Задать вопрос автору статьи

Где хранятся существующие переменные

Переменные среды в Windows 10 и Windows 11

Для начала давайте посмотрим, где хранятся переменные окружения в Windows 10 или 11. Уже потом познакомимся с ними поближе и на примере поймем, как они работают в системе.

  1. Кликните правой кнопкой по вашему компьютеру и зайдите в «Свойства».

Переменные окружения Windows 10 и Windows 11: полный гайд

  1. Если у вас обычная Home-версия – слева выбираем ссылку «Дополнительные параметры системы». Если у вас последняя Pro-версия, тогда в разделе «О программе» в правом блоке листаем в самый низ и находим ссылку с таким же названием.

Переменные окружения Windows 10 и Windows 11: полный гайд

  1. Перейдите во вкладку «Дополнительно» и нажмите по кнопке «Переменные среды…».

Переменные окружения Windows 10 и Windows 11: полный гайд

Далее вы увидите две таблички. В первом столбце указаны «Переменные», которые вы можете использовать. А во втором столбце – это их значения, которые уже используются программами или скриптами. Верхний блок – это переменные локального пользователя, под которым вы сидите. Они могут быть созданы установленными программами или вами. Внизу строгие системные переменные.

Переменные окружения Windows 10 и Windows 11: полный гайд

Также можно посмотреть весь перечень в консоли – открываем командную строку. Далее вводим команду:

set > %homepath%\desktop\set.txt

Переменные окружения Windows 10 и Windows 11: полный гайд

Команда выполняется очень быстро. После этого смотрим на рабочий стол и открываем текстовый файл

set.txt

В нем хранятся все уже существующие переменные, которые вы можете использовать. Все эти переменные мы используем в любом месте, в скриптах или командной строке. Например, в прошлой команде мы уже использовали переменную %homepath% – которая заменяет данные о положении папки:

C:\Users\Имя

Переменные окружения Windows 10 и Windows 11: полный гайд

И еще один важный момент – все переменные обрамляются знаком процента (%) с двух сторон. Размер написанных букв переменных не важен:

%homepath% = %HOMEPATH% = %Homepath%

PATH и PATHEXT

Вы могли заметить две интересные переменные PATH и PATHEXT, которые содержат в себе сразу целый массив значений. Как же с ними работать? – давайте разберем на конкретном примере.

Переменные окружения Windows 10 и Windows 11: полный гайд

Представим себе, что мы запускаем какую-то программу:

program.exe

С допиской переменной PATH. Если посмотреть в значения PATH, можно заметить, что это пути к определенным папкам на любом диске системы. Если вы будете использовать переменную PATH, в скрипте или консольной команде, то система пройдет по всему массиву – то есть по всем выделенным папкам и попробует найти program.exe и запустит его, если найдет. Давайте добавим свою директорию:

  1. Выделите PATH, нажав ЛКМ.
  2. Кликаем по кнопке «Изменить».

Переменные окружения Windows 10 и Windows 11: полный гайд

  1. Жмем «Создать».
  2. Далее вводим новую директорию. Желательно, чтобы эта директория была верной, и папка такая существовала. В конце жмем «ОК».

Переменные окружения Windows 10 и Windows 11: полный гайд

И еще один важный момент – после того как вы добавили новые переменные, надо чтобы они появились в системе. Для этого – или перезагружаем компьютер, или «Проводник». Только после этого переменными можно будет пользоваться. Для перезагрузки проводника, откройте консоль и введите две команды:

taskkill /F /IM explorer.exe

После этого вводим:

explorer.exe

Если вы будете работать с переменными среды в командной строке Windows 10 или Windows 11, то вам нужно также её перезапустить – закрываем и снова открываем приложение.

Ах, да…мы чуть не забыли про переменную PATHEXT, в которой хранятся различные расширения. Работает переменная примерно также. Вы можете не указывать расширение программы или объекта для запуска в скрипте или командной строке. Система автоматически будет брать расширения из массива PATHEXT и перебирать все варианты. Поэтому вместо:

program.exe

Можно просто указать:

program

Создание переменной

Давайте посмотрим, как создать переменную среды в Windows. Делается все очень просто. Выбираем верхний или нижний блок и жмем по кнопке «Создать». Еще раз повторюсь, что верхний блок предназначен для запуска команд под данным локальным пользователем.

Переменные окружения Windows 10 и Windows 11: полный гайд

Вводим «Имя переменной» и значение – куда можно указать путь к папке, файлу или запускаемой программе. Напомню, что здесь вы также можете использовать системные переменные, которые находятся в нижнем блоке. Жмем «ОК».

Переменные окружения Windows 10 и Windows 11: полный гайд

Напомню – чтобы переменная заработала, нужно будет перезагрузить «Проводник» (Explorer.exe). Про то как это сделать я уже писал в прошлой главе. Если остались вопросы и вы хотите получить помощь от портала WiFiGiD.RU – опишите свою проблему в комментариях. Также вы можете писать дополнения и предложения там же.

If by «system environment variables» you refer specifically to system-wide environment variables, then other answers have already covered this. However, if you want to edit both system-wide and user-specific environment variables then most (if not all) of these answers are inapplicable in general case.

Going through «System» and then “Advanced system settings” -> “Environment Variables” will only work for accounts from Administrators group, because only such accounts have access to “Advanced system settings”.

If you attempt do that from a regular user account, then trying to access “Advanced system settings” will trigger an UAC prompt asking you for administrator password. If you enter the password, “Advanced system settings” will successfully open, but any user-specific changes you make there will apply to the corresponding administrator’s account (!), not to your original user’s account.

In order to solve this problem (i.e. in order to give regular users the opportunity to edit their own environment variables) Windows provides another way to access the “Environment Variables” dialog.

Open Control Panel. Open User Accounts applet. On the left-hand side of that applet you will see a link that says Change my environment variables. Click that link, and it will take you to the same “Environment Variables” dialog for your user’s environment variables.

enter image description here

If your user has administrator rights, you will be able to edit both sections of that dialog: user-specific environment variables (upper section) and system-wide environment variables (lower section). If you don’t have administrator rights, you will only be able to edit the upper section: your own user-specific environment variables.

This is the proper way to edit environment variables in all post-UAC versions of Windows, not what is suggested in the majority of the answers above.


Unfortunately, Windows 10 November update (version 1511) destroyed this functionality. The Change my environment variables link no longer works. It is there, but it is dead. So for the post-November version of Windows 10 the correct answer is: it is generally impossible to edit user-specific environment variables in version 1511 of Windows 10 from regular user accounts. Microsoft has destroyed Windows 10 with this update and Windows 10 is now unusable. It will remain the case until they fix these ridiculous bugs in 1511 version of the OS.

For the time being one workaround for non-administrative accounts is to, well, add your user account to Administrators group, logout, log back in, edit the variables using «System» -> “Advanced system settings” method, and then take away administrative rights again…

An alternative workaround is to use PowerShell features as described here
https://technet.microsoft.com/en-us/library/ff730964.aspx


Windows 10 Anniversary Update (version 1607) released August 2, 2016 finally fixed this bug.

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:

  1. Type Advanced system settings in the Start menu search box and select the Best match.
  2. In the System Properties box, click on Environment Variables to open the Environment Variables panel.
Advanced system settings panel in Windows

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.

Environment variables panel

Let’s say you’ve just installed Java and want to add the java path to the EVs. To do this:

  1. Click on New under the User/System variables. This will open up the New User Variable box.
  2. 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.
Adding a new environment variable

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.

Environment variable Edit variable panel

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.

Environmental Variables are dynamic objects which define different elements in a Windows environment. These variables can be used by different programs from anywhere within Windows and provide certain parameters to perform specific tasks.

Creating custom environment variables in Windows assists you in the longer run, as it enables you to run a program or a .exe file from any directory in Windows, and the title of the program would still be recognizable.

If you are using the same path or directory over and over again, it would be better to create a variable and provide a path of your directory and just use that variable instead of having to give complete paths each time.

You can say these variables as shortcuts to your apps. This can make you move around in Windows rather quickly. Before we dig into the process of creating a custom environmental variable, let us briefly discuss a bit about them.

Table of contents

  • Types of Variables
    • System Variables
    • User Variables
  • Use of Environment Variables
  • Creating User Defined Environment Variables
  • Closing Words

Types of Variables

There are two types of environment variables: A system variable and a user variable. Both are combined to make a complete computer environment.

System Variables

System variables are termed global variables and can be accessed or used by any user account on your computer.

User Variables

User variables are termed specific variables, which can only be accessed within the same user account. Other accounts on your computer are not familiar with such variables.

Use of Environment Variables

If you have to go to User Profile, and you have created a system variable with the name “userprofile”. You don’t need to open File Explorer and then navigate to your profile. Just simply access the variable you have created by typing “%userprofile%” into the Start Menu.

How To Create Custom Environment Variables in Windows 10 1

Access variable directly from anywhere

Accessing the variable, in this specific example, will automatically open your current user account.

How To Create Custom Environment Variables in Windows 10 2

Quickly access via environmental variable

Another example of using an environmental variable is while using a .exe file in the Command Prompt. If you have placed a .exe file in the “Downloads” folder, then you will need to provide the path “%userprofile%\Downloads\ABC.exe” each time to use the file. However, if it is declared as a user or system variable, then simply putting in “ABC.exe” will automatically fetch the .exe file, regardless of your current directory in the Command Prompt.

Now you know how these variables are helpful. Let us now show you how you can create your own custom variables and assign a path to save your time and navigate quickly within your OS.

Creating User Defined Environment Variables

Let’s create our own environment variables. Follow the steps below to do so:

  1. Type in sysdm.cpl in Run to open System Properties.
    sysdm
  2. From the System Properties window, switch to the Advanced tab and then click Environmental Variables.
    advanced
  3. From the Environmental Variables window, click New under User or System variables (Your choice).
    New
  4. In the New Variable popup, enter a name for your variable and then enter its complete path in Variable Value. Click Ok when done. In our case, we want to access the “Company” folder so we put the address of that particular folder in “Variable Value” of the new variable.
    ok

A new variable is now added to your environmental variables list.

New variable added

New variable added

Now typing in the name of your environmental variable in Run or Command Prompt will automatically open the desired location.

You can also create environmental variables for .exe files, batch files, etc., and use them to pass parameters and perform certain tasks.

If you wish to know the path for a variable, open the Command Prompt and type “echo” followed by the environmental variable inside percentage (%) signs, as in the following example:

cmd 5

Complete path to environmental variable

In case you do not wish to use a variable in the future or want to edit it, you can delete the variable by selecting it in the Environmental variables window and then clicking Delete, or you may also click Edit to change its path or name.

Closing Words

Creating your own customized variables can be super helpful in cases where you have to use a path over and over again. What methods do you use as shortcuts for opening your favorite programs and folders?

  • Перенос windows server 2008 r2 на windows server 2008 r2
  • Перенести настройки пользователя windows 10
  • Перенос windows 10 на virtualbox
  • Переменные среды windows рабочий стол
  • Переключение между двумя окнами windows