- Windows Environment Variables Tutorial
- What’s Environment Variables
- View Environment Variables
- Sample Values of Environment Variable
- Types of Environment Variable
- How to edit environment variables in Windows 10
- Editing Environment Variables:
- Navigating to Environment Variables Manually
- How to set the path and environment variables in Windows
- Setting the path and variables in Windows 10
- Setting the path and variables in Windows 8
- Setting the path and variables in Windows Vista and Windows 7
- Setting the path and variables in Windows 2000 and Windows XP
- What is the default Windows %PATH%?
- Setting path in the MS-DOS and Windows command line
- Изучаем переменные среды в Windows 10
- Переменные среды Windows
- Переменные PATH и PATHEXT
- Создание переменных среды
- Заключение
Windows Environment Variables Tutorial
What’s Environment Variables
Environment variables are system-wide global variables. They are config parameters and is used by processes. For example, apps need to know the path of your Windows kernal, path of your home dir, paths to search for shell programs, etc.
Windows environment variable names are not case sensitive
View Environment Variables
Press ❖ Window key, then type “environment”
Type in shell c:\Windows\System32\SystemPropertiesAdvanced.exe to launch the GUI app directly.
Windows 10 SystemPropertiesAdvanced 2021-02-04
Sample Values of Environment Variable
Here’s example of env var values as it exists on my system.
One of the most important environment variable is PATH . Here’s a sample value of path (with line break added for easy reading):
value of the environment variable PATH
Types of Environment Variable
There are 3 types of environment variable:
Process Per session. It is temporary. It exist only for the current session in cmd.exe or PowerShell. After you exit the shell, the variables you created are gone. When a shell starts, it gets environment variable from the Windows Registry. User Permanent, stored in Windows Registry. Per user. Each user may have different values.
Examples: home folder HOMEPATH , temp dir ( TEMP and or TMP ).
In Registry, they are at: HKEY_CURRENT_USER\Environment . Machine Permanent, stored in Windows Registry. Per machine. Each machine may have different values.
Examples:
- OS kernal path ( WINDIR )
- processor info ( PROCESSOR_ARCHITECTURE , NUMBER_OF_PROCESSORS , etc)
- application paths ( PATH )
- executable file name extensions ( PATHEXT )
- OS type ( OS )
- current user name ( USERNAME )
In Registry, they are at:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
[see Microsoft Windows Registry Tutorial]
Process environment variable is also known as Local Environment Variable.
User environment variable and Machine environment variable are together also known as System Environment Variable.
Note that you can set any new env vars in any category. Programs have access to all your env vars, but which ones are meaningful to the program is up to the program.
How to edit environment variables in Windows 10
Environment variables are the values that contain all the information regarding system environment. Every process inside Windows OS has a block that contains a set of environment variables and their values. There are two kinds of environment variables i.e. User Environment Variables and System Environment Variables. As the name represents, user environment variables are set for every user while system environment variables are for everyone who uses the system.
Any user working on command prompt or batch scripts will be well aware of environment variables because of the repetition of a value again and again. Every environment variable has two parameters i.e. name and value. So, you can edit or create your own environment variables in order to ease the work for yourself. So, in this guide, I will discuss about the way to edit environment variables in Windows 10.
Editing Environment Variables:
In order to edit environment variables, follow the steps below to access them.
Navigating to Environment Variables Using Command Prompt:
1. If you want to have access to both the variables i.e. user and system variables, then, open an elevated Command Prompt by right clicking over the Start Menu icon and selecting Command Prompt (Admin) from the list.
2. While inside the command prompt, type or copy/paste the following command stated below. You can paste the command by right clicking inside Command prompt and selecting Paste. Hit the Enter key to execute the command.
Command: rundll32.exe sysdm.cpl,EditEnvironmentVariables
3. After hitting Enter, Environment Variables window will pop-up with a section for User variables and another section for System variables.
4. In order to edit a variable, select that variable and press the Edit button to change the Name or Press OK afterwards.
5. If you want to create a new environment variable for yourself, then, click over the New button and type the Name and Value for that particular variable followed by the OK
Navigating to Environment Variables Manually
1. Press Win+ X keys on the keyboard and select System from the list.
2. Inside the System window, click on Advanced system settings located at the left pane.
3. Inside the advanced system settings, click on the Environment Variables button at the bottom and do follow the same procedure to edit environment variables as described above.
How to set the path and environment variables in Windows
Setting the path and environment variables will differ depending on the version of Windows you have on your computer. Choose a link below for your version of Windows.
Administrator privileges are usually required to modify the path and environment variables.
Setting the path and variables in Windows 10
- From the desktop, right-click the very bottom-left corner of the screen to get the Power User Task Menu.
- From the Power User Task Menu, click System.
- In the Settings window, scroll down to the Related settings section and click the System info link.
- In the System window, click the Advanced system settings link in the left navigation pane.
- In the System Properties window, click the Advanced tab, then click the Environment Variablesbutton near the bottom of that tab.
- In the Environment Variables window (pictured below), highlight the Path variable in the System variables section and click the Edit button. Add or modify the path lines with the paths you want the computer to access. Each different directory is separated with a semicolon, as shown below.
You can edit other environment variables by highlighting the variable in the System variables section and clicking Edit. If you need to create a new environment variable, click New and enter the variable name and variable value.
To view and set the path in the Windows command line, use the path command.
Setting the path and variables in Windows 8
- From the desktop, right-click the very bottom-left corner of the screen to get the Power User Task Menu.
- From the Power User Task Menu, click System.
- Click the Advanced System Settings link in the left column.
- In the System Properties window, click the Advanced tab, then click the Environment Variablesbutton near the bottom of that tab.
- In the Environment Variables window (pictured below), highlight the Path variable in the System variables section and click the Edit button. Add or modify the path lines with the paths you want the computer to access. Each different directory is separated with a semicolon, as shown below.
You can edit other environment variables by highlighting the variable in the System variables section and clicking Edit. If you need to create a new environment variable, click New and enter the variable name and variable value.
To view and set the path in the Windows command line, use the path command.
Setting the path and variables in Windows Vista and Windows 7
- From the desktop, right-click the Computer icon and select Properties. If you don’t have a Computer icon on your desktop, click Start, right-click the Computer option in the Start menu, and select Properties.
- Click the Advanced System Settings link in the left column.
- In the System Properties window, click the Advanced tab, then click the Environment Variablesbutton near the bottom of that tab.
- In the Environment Variables window (pictured below), highlight the Path variable in the System variables section and click the Edit button. Add or modify the path lines with the paths you want the computer to access. Each different directory is separated with a semicolon, as shown below.
You can edit other environment variables by highlighting the variable in the System variables section and clicking Edit. If you need to create a new environment variable, click New and enter the Variable name and Variable value.
To view and set the path in the Windows command line, use the path command.
Setting the path and variables in Windows 2000 and Windows XP
The path is now managed by Windows 2000 and Windows XP and not the autoexec.bat or autoexec.nt files, as was done with earlier versions of Windows. To change the system environment variables, follow the steps below.
- From the desktop, right-click My Computer and click Properties. If you don’t have a My Computer icon on your desktop, click Start, right-click the My Computer option in the Start menu, and select Properties.
- In the System Propertieswindow, click the Advancedtab.
- In the Advanced section, click the Environment Variablesbutton.
- In the Environment Variables window (as shown below), highlight the Path variable in the System Variable section and click the Edit button. Add or modify the path lines with the paths you want the computer to access. Each different directory is separated with a semicolon, as shown below.
You can edit other environment variables by highlighting the variable in the System variables section and clicking Edit. If you need to create a new environment variable, click New and enter the Variable name and Variable value.
To view and set the path in the Windows command line, use the path command.
What is the default Windows %PATH%?
The path is based on programs installed on the computer, so there is no «default path.» However, the Windows minimum path is often the path below.
Keep in mind that as you install programs, the path is updated with the paths for the newly installed programs. So, if you have erased your path after installing other programs, those programs may be affected.
Setting path in the MS-DOS and Windows command line
To view and set the path in MS-DOS and in the Windows command line, use the path command.
Изучаем переменные среды в Windows 10
Переменные среды Windows
Получить информацию о существующих переменных можно в свойствах системы. Для этого кликаем по ярлыку Компьютера на рабочем столе правой кнопкой мыши и выбираем соответствующий пункт.
Переходим в «Дополнительные параметры».
В открывшемся окне с вкладкой «Дополнительно» нажимаем кнопку, указанную на скриншоте ниже.
Здесь мы видим два блока. Первый содержит пользовательские переменные, а второй системные.
Если требуется просмотреть весь перечень, запускаем «Командную строку» от имени администратора и выполняем команду (вводим и нажимаем ENTER).
На рабочем столе появится файл с названием «set.txt», в котором будут указаны все переменные окружения, имеющиеся в системе.
Все их можно использовать в консоли или скриптах для запуска программ или поиска объектов, заключив имя в знаки процента. Например, в команде выше вместо пути
Примечание: регистр при написании переменных не важен. Path=path=PATH
Переменные PATH и PATHEXT
Если с обычными переменными все понятно (одна ссылка – одно значение), то эти две стоят особняком. При детальном рассмотрении видно, что они ссылаются сразу на несколько объектов. Давайте разберемся, как это работает.
«PATH» позволяет запускать исполняемые файлы и скрипты, «лежащие» в определенных каталогах, без указания их точного местоположения. Например, если ввести в «Командную строку»
система осуществит поиск по папкам, указанным в значении переменной, найдет и запустит соответствующую программу. Этим можно воспользоваться в своих целях двумя способами:
- Поместить необходимый файл в одну из указанных директорий. Полный список можно получить, выделив переменную и нажав «Изменить».
Создать свою папку в любом месте и прописать путь к ней. Для этого (после создания директории на диске) жмем «Создать», вводим адрес и ОК.
%SYSTEMROOT% определяет путь до папки «Windows» независимо от буквы диска.
Затем нажимаем ОК в окнах «Переменные среды» и «Свойства системы».
Для применения настроек, возможно, придется перезапустить «Проводник». Сделать это быстро можно так:
Открываем «Командную строку» и пишем команду
taskkill /F /IM explorer.exe
Все папки и «Панель задач» исчезнут. Далее снова запускаем «Проводник».
Еще один момент: если вы работали с «Командной строкой», ее также следует перезапустить, то есть консоль не будет «знать», что настройки изменились. Это же касается и фреймворков, в которых вы отлаживаете свой код. Также можно перезагрузить компьютер или выйти и снова зайти в систему.
Теперь все файлы, помещенные в «C:\Script» можно будет открывать (запускать), введя только их название.
«PATHEXT», в свою очередь, дает возможность не указывать даже расширение файла, если оно прописано в ее значениях.
Принцип работы следующий: система перебирает расширения по очереди, пока не будет найден соответствующий объект, причем делает это в директориях, указанных в «PATH».
Создание переменных среды
Создаются переменные просто:
- Нажимаем кнопку «Создать». Сделать это можно как в пользовательском разделе, так и в системном.
Вводим имя, например, «desktop». Обратите внимание на то, чтобы такое название еще не было использовано (просмотрите списки).
В поле «Значение» указываем путь до папки «Рабочий стол».
Нажимаем ОК. Повторяем это действие во всех открытых окнах (см. выше).
Для примера переделаем команду, которую мы использовали для получения списка (самая первая в статье). Теперь нам вместо
потребуется ввести только
Заключение
Использование переменных окружения позволяет значительно сэкономить время при написании скриптов или взаимодействии с системной консолью. Еще одним плюсом является оптимизация создаваемого кода. Имейте в виду, что созданные вами переменные отсутствуют на других компьютерах, и сценарии (скрипты, приложения) с их использованием работать не будут, поэтому перед тем, как передавать файлы другому пользователю, необходимо уведомить его об этом и предложить создать соответствующий элемент в своей системе.