Как создать environment variable в 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

Все способы:

  • Переменные среды Windows
    • Переменные PATH и PATHEXT
    • Создание переменных среды
    • Заключение
  • Вопросы и ответы: 6

Переменная среды (переменная окружения) – это короткая ссылка на какой-либо объект в системе. С помощью таких сокращений, например, можно создавать универсальные пути для приложений, которые будут работать на любых ПК, независимо от имен пользователей и других параметров.

Переменные среды Windows

Получить информацию о существующих переменных можно в свойствах системы. Для этого кликаем по ярлыку Компьютера на рабочем столе правой кнопкой мыши и выбираем соответствующий пункт.

Переход к свойствам операционной системы с рабочего стола Windows 10

Переходим в «Дополнительные параметры».

Переход к дополнительным параметрам системы в ОС Windows 10

В открывшемся окне с вкладкой «Дополнительно» нажимаем кнопку, указанную на скриншоте ниже.

Переход к обзору переменных среды в ОС Windows 10

Здесь мы видим два блока. Первый содержит пользовательские переменные, а второй системные.

Раздел настройки переменных среды в Windows 10

Если требуется просмотреть весь перечень, запускаем «Командную строку» от имени администратора и выполняем команду (вводим и нажимаем ENTER).

set > %homepath%\desktop\set.txt

Создание текстового документа со списком переменных среды из Командной строки Windows 10

Подробнее: Как открыть «Командную строку» в Windows 10

На рабочем столе появится файл с названием «set.txt», в котором будут указаны все переменные окружения, имеющиеся в системе.

Текстовый документ со списком переменных среды Windows 10

Все их можно использовать в консоли или скриптах для запуска программ или поиска объектов, заключив имя в знаки процента. Например, в команде выше вместо пути

C:\Users\Имя_пользователя

мы использовали

%homepath%

Примечание: регистр при написании переменных не важен. Path=path=PATH

Переменные PATH и PATHEXT

Если с обычными переменными все понятно (одна ссылка – одно значение), то эти две стоят особняком. При детальном рассмотрении видно, что они ссылаются сразу на несколько объектов. Давайте разберемся, как это работает.

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

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

explorer.exe

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

  • Поместить необходимый файл в одну из указанных директорий. Полный список можно получить, выделив переменную и нажав «Изменить».
    Переход к изменению переменной среды PATH в ОС Windows 10

  • Создать свою папку в любом месте и прописать путь к ней. Для этого (после создания директории на диске) жмем «Создать», вводим адрес и ОК.

    Добавление значения переменной PATH в Windows 10

    %SYSTEMROOT% определяет путь до папки «Windows» независимо от буквы диска.

    Затем нажимаем ОК в окнах «Переменные среды» и «Свойства системы».

    Применение настроек переменных окружения в Windows 10

Для применения настроек, возможно, придется перезапустить «Проводник». Сделать это быстро можно так:

Открываем «Командную строку» и пишем команду

taskkill /F /IM explorer.exe

Завершение работы Проводника из Командной строки в Windows 10

Все папки и «Панель задач» исчезнут. Далее снова запускаем «Проводник».

explorer

Перезапуск Проводника из Командной строки в Windows 10

Еще один момент: если вы работали с «Командной строкой», ее также следует перезапустить, то есть консоль не будет «знать», что настройки изменились. Это же касается и фреймворков, в которых вы отлаживаете свой код. Также можно перезагрузить компьютер или выйти и снова зайти в систему.

Теперь все файлы, помещенные в «C:\Script» можно будет открывать (запускать), введя только их название.

Запуск файла с помощью переменной среды PATH в Windows 10

«PATHEXT», в свою очередь, дает возможность не указывать даже расширение файла, если оно прописано в ее значениях.

Значения переменной среды PATHEXT в Windows 10

Принцип работы следующий: система перебирает расширения по очереди, пока не будет найден соответствующий объект, причем делает это в директориях, указанных в «PATH».

Запуск приложения с помощью переменной PATHEXT в Windows 10

Создание переменных среды

Создаются переменные просто:

  1. Нажимаем кнопку «Создать». Сделать это можно как в пользовательском разделе, так и в системном.
    Переход к созданию переменной среды в Windows 10

  2. Вводим имя, например, «desktop». Обратите внимание на то, чтобы такое название еще не было использовано (просмотрите списки).

    Присвоение имени новой переменной среды в Windows 10

  3. В поле «Значение» указываем путь до папки «Рабочий стол».

    C:\Users\Имя_пользователя\Desktop

    Присвоение значения новой переменной среды в Windows 10

  4. Нажимаем ОК. Повторяем это действие во всех открытых окнах (см. выше).

    Применение настроек при создании новой переменной среды в Windows 10

  5. Перезапускаем «Проводник» и консоль или целиком систему.
  6. Готово, новая переменная создана, увидеть ее можно в соответствующем списке.

    Расположение новой пользовательской переменной среды в списке в Windows 10

Для примера переделаем команду, которую мы использовали для получения списка (самая первая в статье). Теперь нам вместо

set > %homepath%\desktop\set.txt

потребуется ввести только

set > %desktop%\set.txt

Заключение

Использование переменных окружения позволяет значительно сэкономить время при написании скриптов или взаимодействии с системной консолью. Еще одним плюсом является оптимизация создаваемого кода. Имейте в виду, что созданные вами переменные отсутствуют на других компьютерах, и сценарии (скрипты, приложения) с их использованием работать не будут, поэтому перед тем, как передавать файлы другому пользователю, необходимо уведомить его об этом и предложить создать соответствующий элемент в своей системе.

Наша группа в TelegramПолезные советы и помощь

Download Article

Download Article

This wikiHow teaches how to add new environment variables in Windows 10. Environment variables are useful to specify paths internally in the OS for specific programs. It is basically stored in the form of a name and value pair. OS has a lot of builtin environment variables like ‘PATH’ where paths to installed Softwares are stored. Stick to this article, to find out how to add environment variables in Windows 10.

  1. Step 1 Locate the "This PC" icon on your system.

    You may find it on your desktop screen. You can go to your desktop by pressing Ctrl+D.

  2. 2

    Right-click on the «This PC» icon. This will show a small popup, with few options.

    Advertisement

  3. Step 3 Click on the "Properties" option.

    You may find this in the last position below the «Rename» option. This will open a new window with all the system details like RAM, Processor, OS, etc.

  4. Step 4 Click or double click on "Advanced System Settings".

    You may find this option on the left-hand side of the newly opened window (System Details). This option is below the «System Protection» option.

  5. 4_click_environment_variables.png

    5

    Click on Environment Variables. After clicking, it will show a new window dialog called «Environment Variables».

  6. 5_decide_variables.png

    6

    Decide which variable to add (User / System). Click the New option in any (User/System) section.

  7. 6_add_variables.png

    7

    Add the variable name and variable value and click OK. In variable_name, you can give a name to your user variable and specify PATH in the variable_value, finally, click «ok» to save the changes.

  8. Step 8 View the environment variables.

    After saving a new variable with path, you can see the entry of variables.

  9. Step 9 Click OK.

    After clicking OK, you will have successfully created a new User variable with a PATH attached to it.

  10. Advertisement

Ask a Question

200 characters left

Include your email address to get a message when this question is answered.

Submit

Advertisement

Thanks for submitting a tip for review!

About This Article

Thanks to all authors for creating a page that has been read 26,042 times.

Is this article up to date?

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

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.

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.
  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?

Environment variables in an operating system are values that contain information about the system environment, and the currently logged in user. They existed in OSes before Windows as well, such as MS-DOS. Applications or services can use the information defined by environment variables to determine various things about the OS, for example, to detect the number of processes, the currently logged in user’s name, the folder path to the current user’s profile or the temporary files directory. Today, we will review a number of methods you can use to create a new user and system environment variable in Windows 10.

Windows 10 has several types of environment variables: user variables, system variables, process variables and volatile variables. User environment variables are accessible to all apps which run in the current user context, system environment variables apply to all users and processes on the PC; process variables are applicable only to a specific process and volatile variables are those which exist only for the current logon session. Most interesting of these are user, system and process variables, as we can modify them.

Example: A user environment variable.

Example: A system environment variable.

Windows 10 System Environment Variable

Windows 10 stores user environment variables under the following Registry key:

HKEY_CURRENT_USER\Environment

System variables are stored under the following key:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment

Reference: How to see names and values of environment variables in Windows 10

  1. Open the classic Control Panel.
  2. Navigate to Control Panel\User Accounts\User Accounts.
  3. On the left, click on the Change my environment variables link.
    Windows 10 Change My Environment Variables Link

  4. In the next dialog, click the New button under the User variables for <username> section.
    Windows 10 New User Variable

  5. Enter a variable name you want to create, then enter a variable value you want to assign to it. The dialog allows browsing for a file or folder to save your time.
    Windows 10 New User Variable Dialog

  6. Click the OK button, and you are done.

Note: Re-open the required apps (e.g. Command Prompt) to make them read your new environment variable.

Tip: There are a number of other methods you can use to open the environment variables editor in Windows 10. First of all, you can create a special shortcut to open it directly. See Create Environment Variables Shortcut in Windows 10.

Also, there’s a special RunDLL command that you can use (Press Win + R and copy-paste it to the Run box):

rundll32.exe sysdm.cpl,EditEnvironmentVariables

Finally, you can right-click the This PC icon in File Explorer and select Properties from the context menu. Click the «Advanced System Settings» link on the left. In the next dialog, «System Properties», you will see the Environment Variables… button in the bottom of the Advanced tab. Moreover, the Advanced System Settings dialog can be directly opened with the systempropertiesadvanced command entered into the Run dialog.

Create a User Environment Variable in Command Prompt

  1. Open a new command prompt
  2. Type the following command: setx <variable_name> "<variable_value>"
  3. Substitute <variable_name> with the actual name of the variable you want to create.
  4. Substitute "<variable_value>" with the value you want to assign to your variable.
    Windows 10 New User Variable Command Prompt 1

Do not forget to restart your apps (e.g. Command Prompt) to make them read your new environment variable.

Windows 10 New User Variable Command Prompt 2

The setx command is a console tool that can be used to set or unset user and system environment variables. In the general case, the syntax is as follows:

setx variable_name variable_value — set an environment variable for the current user.

setx /M variable_name  variable_value — set an environment variable for all user (system-wide).

Type setx /? in a command prompt to see more details about this tool.

Create a User Environment Variable in PowerShell

  1. Open PowerShell.
  2. Type the following command:
    [Environment]::SetEnvironmentVariable("<variable_name>", "<variable_value>" ,"User")
  3. Substitute <variable_name> with the actual name of the variable you want to create.
  4. Substitute "<variable_value>" with the value you want to assign to your variable.
    Windows 10 New User Variable PowerShell

Similarly, you can create a system environment variable.

Create a System Environment Variable

  1. Open the Run dialog (Win + R), and execute the command systempropertiesadvanced .

  2. In the System Properties dialog, switch to the Advanced tab. Click on the Environment Variables… button.
    Windows 10 New System Environment Variable 1

  3. In the next dialog, click the New button under the System variables section.
    Windows 10 New System Environment Variable 2

  4. Set the desired name for a variable you want to create, and specify its value, then click OK.
    Windows 10 New System Environment Variable 3

Create a User Environment Variable in Command Prompt

  1. Open a new command prompt as Administrator.
  2. Type the following command: setx /M <variable_name> "<variable_value>"
  3. Substitute <variable_name> with the actual name of the variable you want to create.
  4. Substitute "<variable_value>" with the value you want to assign to your variable.
    Windows 10 Cmd New System Environment Vairable

The /M switch makes the setx command create a system variable.

Create a System Environment Variable in PowerShell

  1. Open PowerShell as Administrator. Tip: You can add «Open PowerShell As Administrator» context menu.
  2. Type the following command:
    [Environment]::SetEnvironmentVariable("<variable_name>", "<variable_value>" ,"Machine")
  3. Substitute <variable_name> with the actual name of the variable you want to create.
  4. Substitute "<variable_value>" with the value you want to assign to your variable.
    Windows 10 PowerShell New System Environment Vairable

The last parameter of the SetEnvironmentVariable call tells it to register the given variable as a system variable.

That’s it.

Related articles:

  • Create Environment Variables Shortcut in Windows 10
  • How to see names and values of environment variables in Windows 10
  • See names and values of environment variables for a process in Windows 10

Support us

Winaero greatly relies on your support. You can help the site keep bringing you interesting and useful content and software by using these options:

If you like this article, please share it using the buttons below. It won’t take a lot from you, but it will help us grow. Thanks for your support!

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Windows 7 ultimate ru x32 x64 bit
  • Что ждет windows в будущем
  • Driver epson px660 windows 10
  • Windows 7 ultimate 86bit
  • Как подключить беспроводную клавиатуру logitech к компьютеру windows 10