Windows setting env variables

Содержание
  1. How to set the path and environment variables in Windows
  2. Setting the path and variables in Windows 10
  3. Setting the path and variables in Windows 8
  4. Setting the path and variables in Windows Vista and Windows 7
  5. Setting the path and variables in Windows 2000 and Windows XP
  6. What is the default Windows %PATH%?
  7. Setting path in the MS-DOS and Windows command line
  8. Windows Environment Variables Tutorial
  9. What’s Environment Variables
  10. View Environment Variables
  11. Sample Values of Environment Variable
  12. Types of Environment Variable
  13. HowTo: Set an Environment Variable in Windows — Command Line and Registry
  14. Print environment variables
  15. Command Prompt
  16. Command Prompt — C:\>
  17. Output
  18. Command Prompt — C:\>
  19. Output
  20. Windows PowerShell
  21. Windows PowerShell — PS C:\>
  22. Output
  23. Windows PowerShell — PS C:\>
  24. Output
  25. Set Environment Variables
  26. User Variables
  27. Command Prompt — C:\>
  28. Command Prompt — C:\>
  29. Output
  30. System Variables
  31. Command Prompt — C:\>
  32. Registry
  33. Printing Environment Variables
  34. Переменные среды в Windows: использование, список и таблицы
  35. Пример использования переменной среды Windows
  36. Как посмотреть переменные среды Windows 10
  37. Доступ к переменным средам из реестра Windows
  38. Как посмотреть все переменные среды в командной строке
  39. Открытие списка переменных среды в Windows PowerShell
  40. Создание переменной среды в Windows
  41. Список переменных среды Windows в таблице
  42. Выводы статьи

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

  1. From the desktop, right-click the very bottom-left corner of the screen to get the Power User Task Menu.
  2. From the Power User Task Menu, click System.
  3. In the Settings window, scroll down to the Related settings section and click the System info link.
  4. In the System window, click the Advanced system settings link in the left navigation pane.
  5. In the System Properties window, click the Advanced tab, then click the Environment Variablesbutton near the bottom of that tab.
  6. 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

  1. From the desktop, right-click the very bottom-left corner of the screen to get the Power User Task Menu.
  2. From the Power User Task Menu, click System.
  3. Click the Advanced System Settings link in the left column.
  4. In the System Properties window, click the Advanced tab, then click the Environment Variablesbutton near the bottom of that tab.
  5. 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

  1. 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.
  2. Click the Advanced System Settings link in the left column.
  3. In the System Properties window, click the Advanced tab, then click the Environment Variablesbutton near the bottom of that tab.
  4. 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.

Читайте также:  Как остановить dhcp сервер linux

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.

  1. 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.
  2. In the System Propertieswindow, click the Advancedtab.
  3. In the Advanced section, click the Environment Variablesbutton.
  4. 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 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.

HowTo: Set an Environment Variable in Windows — Command Line and Registry

Environment variables are not often seen directly when using Windows. However there are cases, especially when using the command line, that setting and updating environment variables is a necessity. In this series we talk about the various approaches we can take to set them. In this article we look at how to interface with environment variables using the Command Prompt and Windows PowerShell. We also note where in the registry the environment variables are set, if you needed to access them in such a fashion.

You can use environment variables in the values of other environment variables. It is then helpful to be able to see what environment variables are set already. This is how you do it:

Читайте также:  Как удалить windows если установлена еще windows

Command Prompt

List all environment variables

Command Prompt — C:\>

Output

Print a particular environment variable:

Command Prompt — C:\>

Output

Windows PowerShell

List all environment variables

Windows PowerShell — PS C:\>

Output

Print a particular environment variable:

Windows PowerShell — PS C:\>

Output

Set Environment Variables

To set persistent environment variables at the command line, we will use setx.exe . It became part of Windows as of Vista/Windows Server 2008. Prior to that, it was part of the Windows Resource Kit. If you need the Windows Resource Kit, see Resources at the bottom of the page.

setx.exe does not set the environment variable in the current command prompt, but it will be available in subsequent command prompts.

User Variables

Command Prompt — C:\>

Open a new command prompt.

Command Prompt — C:\>

Output

System Variables

To edit the system variables, you’ll need an administrative command prompt. See HowTo: Open an Administrator Command Prompt in Windows to see how.

Command Prompt — C:\>

Registry

The location of the user variables in the registry is: HKEY_CURRENT_USER\ Environment . The location of the system variables in the registry is: HKEY_LOCAL_MACHINE\ SYSTEM\ CurrentControlSet\ Control\ Session Manager\ Environment .

When setting environment variables through the registry, they will not recognized immediately. One option is to log out and back in again. However, we can avoid logging out if we send a WM_SETTINGCHANGE message, which is just another line when doing this programatically, however if doing this on the command line it is not as straightforward.

One way is to get this message issued is to open the environment variables in the GUI, like we do in HowTo: Set an Environment Variable in Windows — GUI; we do not need to change anything, just open the Environment Variables window where we can see the environment variables, then hit OK .

Another way to get the message issued is to use setx , this allows everything to be done on the command line, however requires setting at least one environment variable with setx .

Printing Environment Variables

With Windows XP, the reg tool allows for accessing the registry from the command line. We can use this to look at the environment variables. This will work the same way in the command prompt or in powershell. This technique will also show the unexpanded environment variables, unlike the approaches shown for the command prompt and for powershell.

Переменные среды в Windows: использование, список и таблицы

Переменная среды (environment variable) — текстовая короткая ссылка на элемент операционной системы Windows, предназначенная для получения быстрого доступа к объекту системы, или к данным о каталогах и конфигурации компьютера. Переменная среды (переменная окружения) позволяет быстро перейти к нужному месту на компьютере, без использования имени пользователя или полного пути к объекту.

Переменные окружения Windows используются в командной строке, в диалоговом окне «Выполнить» и адресной строке Проводника. Переменная среды может содержать информацию о настройках системы или данные о текущем пользователе компьютера.

Переменные среды Windows делятся на два вида:

  • Пользовательские переменные среды — содержат указания пути к пользовательским каталогам.
  • Системные переменные среды — содержат информацию о каталогах ОС и конфигурации ПК.

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

Переменные окружения часто используются при написании скриптов, или при работе в командной строке. Короткие переменные можно использовать вместо полного пути до файла или папки, например, при создании ярлыков, при вводе пути к объекту.

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

Рассмотрим следующий пример: пользователю нужно открыть системную папку «AppData», в которой находятся различные данные программ, установленных в операционную систему Windows. Скрытая папка «AppData» находится в профиле пользователя, обычно на диске «C:». Данные приложений расположены по пути:

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

При помощи переменной «%APPDATA%» (переменная используется без кавычек) можно сразу открыть нужную директорию в системе, без ввода имени пользователя, включения отображения скрытых папок, ввода полного пути. Это экономит много времени.

Чтобы открыть нужный каталог достаточно лишь ввести «%APPDATA%» в поле поиска Windows, в адресную строку Проводника или в диалоговое окно «Выполнить», а затем нажать на клавишу «Enter».

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

Пользователь может самостоятельно создавать переменные среды или изменять существующие. В статье мы рассмотрим несколько способов просмотра переменных среды и самостоятельное создание переменной. В руководстве вы найдете таблицу со списком переменных, применяемых в операционных системах Windows 10, Windows 8.1, Windows 8, Windows 7.

Читайте также:  Lenovo ideapad s530 windows

Как посмотреть переменные среды Windows 10

Сейчас мы посмотрим, как получить доступ к переменным средам в операционной системе Windows 10. В других версиях Windows необходимо выполнить аналогичные действия.

Чтобы посмотреть переменные окружения Windows 10, выполните следующее:

  1. Нажмите на клавиши» «Win» + «R».
  2. В окне «Выполнить» введите команду: «systempropertiesadvanced» (без кавычек), а затем нажмите на кнопку «ОК».
  3. В окне «Свойства системы», во вкладке «Дополнительно» нажмите на кнопку «Переменные среды…».

  1. В окне «Переменные среды» отображаются пользовательские переменные среды и системные переменные среды.

Доступ к переменным средам из реестра Windows

Есть возможность получить доступ к переменным средам из системного реестра Windows. Пользователю нужно будет открыть редактор реестра, а затем пройти по пути до определенной ветки.

Системные переменные среды находятся по следующему пути:

Переменные среды локального пользователя расположены в следующей ветке реестра:

Вы можете создать в редакторе реестра новые переменные или изменить существующие.

Как посмотреть все переменные среды в командной строке

Пользователь может получить список переменных среды при помощи системного инструмента — командной строки Windows.

В cmd переменные среды открываются следующим образом:

  1. Запустите командную строку от имени администратора.
  2. Выполните команду:

Для получения списка переменных в виде текстового файла, выполните в командной строке команду:

После выполнения этой команды, на Локальном диске «C:» появится текстовый файл с именем «Variables» (имя можно использовать любое), в котором находится список переменных среды Windows.

На моем компьютере файл имеет следующее содержание:

Открытие списка переменных среды в Windows PowerShell

Открытие списка переменных среды возможно при помощи системного средства Windows PowerShell.

Выполните следующие действия:

  1. Запустите Windows PowerShell от имени администратора.
  2. Введите команду, а затем нажмите на клавишу «Enter»:
  1. В окне PowerShell откроется список переменных среды Windows.

Создание переменной среды в Windows

Пользователь может самостоятельно создать новую переменную для открытия директорий на компьютере, или для запуска программ.

  1. В окне «Переменные среды» выберите одну из групп переменных: пользовательские или системные переменные.
  2. Нажмите на кнопку «Создать…».

На этом примере я создам отдельную переменную среды для запуска программы TeamViewer.

  1. В окне «Изменение пользовательской переменной» добавьте имя переменной, а в поле «Значение переменной:» введите полный путь к исполняемому файлу.

  1. В окне переменных сред добавилась новая переменная. Нажмите на кнопку «ОК» для применения изменений.

  1. В диалоговом окне «Выполнить» введите «%Имя_переменной%», в нашем случае, «%TeamViewer%», нажмите на кнопку «ОК».

  1. На Рабочем столе компьютера откроется окно запущенной программы.

Подобным способом, после ввода переменной в адресную строку Проводника, выполняется запуск программы или открытие директории на ПК.

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

Если добавить в переменную среды Path Windows путь к директории с исполняемым файлом, например, для браузера Google Chrome: C:Program Files (x86)GoogleChromeApplication , то программа запустится из командной строки, после выполнения команды «chrome», без ввода полного пути к исполняемому файлу.

При необходимости, пользователь может удалить ненужную переменную из операционной системы Windows.

Список переменных среды Windows в таблице

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

Переменная Назначение Значение переменной
%ALLUSERSPROFILE% Папка ProgramData C:\ProgramData
%APPDATA% Папка размещения данных программ C:\Users\User\AppData\Roaming
%CommonProgramFiles% Папка Common Files в Program Files C:\Program FilesCommon Files
%CommonProgramW6432% Папка Common Files в Program Files C:\Program Files\Common Files
%COMPUTERNAME% Имя компьютера DESKTOP-XXXXXXX
%ComSpec% Запуск командной строки C:\WINDOWS\system32\cmd.exe
%DriverData% Папка DriverData C:\Windows\System32\Drivers\DriverData
%HOMEDRIVE% Системный диск C:
%HOMEPATH% Папка профиля пользователя C:\Users\User
%LOCALAPPDATA% Папка локальных данных приложений C:\Users\User\AppData\Local
%LOGONSERVER% Имя контроллера домена \DESKTOP-XXXXXXX
%NUMBER_OF_PROCESSORS% Количество потоков процессора
%OneDrive% Папка OneDrive C:\Users\User\OneDrive
%Path% Путь поиска исполняемых файлов C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;…
%PATHEXT% Исполняемые расширения файлов .COM; .EXE; .BAT; .CMD; .VBS; .VBE; .JS; .JSE; .WSF; .WSH; .MSC
%PROCESSOR_ARCHITECTURE% Архитектура процессора AMD64; x86; IA64
%PROCESSOR_IDENTIFIER% Описание процессора
%PROCESSOR_LEVEL% Номер модели процессора
%PROCESSOR_REVISION% Ревизия процессора
%ProgramData% Папка ProgramData C:\ProgramData
%ProgramFiles% Папка ProgramFiles C:\Program Files
%ProgramFiles(x86)% Папка ProgramFiles(x86) C:\Program Files (x86)
%ProgramW6432% Папка ProgramFiles C:\Program Files
%PROMPT% Возвращение параметров командной строки
%PSModulePath% Пути к расположению модулей PowerShell C:\Program Files\WindowsPowerShell\Modules;C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules
%PUBLIC% Папка «Общие» в профиле пользователей C:\Users\Public
%SystemDrive% Системный диск с Windows C:
%SystemRoot% Папка Windows C:\Windows
%TEMP% Временный каталог C:\Users\User\AppData\Local\Temp
%TMP% Временный каталог C:\Users\User\AppData\Local\Temp
%USERDOMAIN% Имя домена DESKTOP-XXXXXXX
%USERNAME% Имя пользователя User
%USERPROFILE% Профиль пользователя C:\Users\User
%Windir% Папка Windows C:\Windows

Выводы статьи

Переменные окружения Windows позволяют пользователю экономить время во время работы на компьютере. Переменными средами Windows могут пользоваться обычные пользователи или системные администраторы для быстрого доступа к объектам операционной системы, чтобы открыть нужную директорию на компьютере, или запустить программу.

Оцените статью