- Environment Variables
- Changing Environment Variables
- Example 1
- Example 2
- Example 3
- How to change environment variables on Windows 10
- Step by step
- Applying the change
- Как изменить переменные среды в Windows 7
- Зачем редактировать переменные
- Способ 1: Свойства «Компьютера»
- Способ 2: «Командная строка»
- 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
Environment Variables
Every process has an environment block that contains a set of environment variables and their values. There are two types of environment variables: user environment variables (set for each user) and system environment variables (set for everyone).
By default, a child process inherits the environment variables of its parent process. Programs started by the command processor inherit the command processor’s environment variables. To specify a different environment for a child process, create a new environment block and pass a pointer to it as a parameter to the CreateProcess function.
The command processor provides the set command to display its environment block or to create new environment variables. You can also view or modify the environment variables by selecting System from the Control Panel, selecting Advanced system settings, and clicking Environment Variables.
Each environment block contains the environment variables in the following format: Var1=Value1\0
Var2=Value2\0
Var3=Value3\0
.
VarN=ValueN\0\0
The name of an environment variable cannot include an equal sign (=).
The GetEnvironmentStrings function returns a pointer to the environment block of the calling process. This should be treated as a read-only block; do not modify it directly. Instead, use the SetEnvironmentVariable function to change an environment variable. When you are finished with the environment block obtained from GetEnvironmentStrings, call the FreeEnvironmentStrings function to free the block.
Calling SetEnvironmentVariable has no effect on the system environment variables. To programmatically add or modify system environment variables, add them to the HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment registry key, then broadcast a WM_SETTINGCHANGE message with lParam set to the string «Environment». This allows applications, such as the shell, to pick up your updates.
The maximum size of a user-defined environment variable is 32,767 characters. There is no technical limitation on the size of the environment block. However, there are practical limits depending on the mechanism used to access the block. For example, a batch file cannot set a variable that is longer than the maximum command line length.
Windows ServerВ 2003 and WindowsВ XP: The maximum size of the environment block for the process is 32,767 characters. Starting with WindowsВ Vista and Windows ServerВ 2008, there is no technical limitation on the size of the environment block.
The GetEnvironmentVariable function determines whether a specified variable is defined in the environment of the calling process, and, if so, what its value is.
To retrieve a copy of the environment block for a given user, use the CreateEnvironmentBlock function.
To expand environment-variable strings, use the ExpandEnvironmentStrings function.
Changing Environment Variables
Each process has an environment block associated with it. The environment block consists of a null-terminated block of null-terminated strings (meaning there are two null bytes at the end of the block), where each string is in the form:
All strings in the environment block must be sorted alphabetically by name. The sort is case-insensitive, Unicode order, without regard to locale. Because the equal sign is a separator, it must not be used in the name of an environment variable.
Example 1
By default, a child process inherits a copy of the environment block of the parent process. The following example demonstrates how to create a new environment block to pass to a child process using CreateProcess.
This example uses the code in example three as the child process, Ex3.exe.
Example 2
Altering the environment variables of a child process during process creation is the only way one process can directly change the environment variables of another process. A process can never directly change the environment variables of another process that is not a child of that process.
If you want the child process to inherit most of the parent’s environment with only a few changes, retrieve the current values using GetEnvironmentVariable, save these values, create an updated block for the child process to inherit, create the child process, and then restore the saved values using SetEnvironmentVariable, as shown in the following example.
This example uses the code in example three as the child process, Ex3.exe.
Example 3
The following example retrieves the process’s environment block using GetEnvironmentStrings and prints the contents to the console.
How to change environment variables on Windows 10
📅 August 31, 2018 ⏱ 1 min read
Here is a guide to editing environment variables on Windows 10! Please note, if you are specifically looking to modify the PATH environment variable, then see Add to the PATH on Windows 10.
Step by step
- Open the Start Search, type in “env”, and choose “Edit the system environment variables”:
- Click the “Environment Variables…” button.
Set the environment variables as needed.
- The New button adds an additional variable
- The Edit button modifies the selected variable
- The Delete button deletes the selected variable
Applying the change
Due to how Windows applies environment variables, you most likely need to restart apps for them to pick up the change, including explorer.exe . Restarting the machine is reccomended (but not required) and ensures all apps are run with the PATH change.
To test it, in new PowerShell window, type:
Written by Ryan Hoffman, an experienced team leader, certified Scrum Master and software architect.
Contact RyanFollow Ryan on Twitter
Как изменить переменные среды в Windows 7
Переменная среды (окружения) в Виндовс хранит информацию о настройках ОС и пользовательских данных. Обозначается она с помощью парного символа «%», например:
С помощью этих переменных можно передавать необходимую информацию операционной системе. Например, %PATH% хранит список директорий, в которых Виндовс ищет исполняемые файлы, если путь к ним не задан явно. %TEMP% хранит временные файлы, а %APPDATA% — настройки программ пользователя.
Зачем редактировать переменные
Изменение переменных среды может помочь, если вы хотите перенести папку «Temp» или «AppData» в другое место. Редактирование %PATH% даст возможность запускать программы из «Командной строки», не указывая каждый раз длинный путь к файлу. Давайте рассмотрим методы, которые помогут в достижении этих целей.
Способ 1: Свойства «Компьютера»
В качестве примера программы, которую необходимо запустить, используем Skype. Попытавшись активировать это приложение из «Командной строки», вы получите такую ошибку:
Это происходит потому, что вы не задали полный путь к исполняемому файлу. В нашем случае полный путь выглядит вот так:
«C:\Program Files (x86)\Skype\Phone\Skype.exe»
Чтобы это не повторять каждый раз, давайте добавим директорию Скайпа в переменную %PATH%.
- В меню «Пуск» нажмите правой кнопкой мыши на «Компьютер» и выберите «Свойства».
Затем перейдите на «Дополнительные параметры системы».
На вкладке «Дополнительно» нажмите на «Переменные среды».
Откроется окно с различными переменными. Выберите «Path» и нажмите «Изменить».
Теперь необходимо дописать путь к нашей директории.
Путь нужно указывать не к самому файлу, а к папке, в которой он находится. Обратите внимание, что разделителем между директориями является «;».
C:\Program Files (x86)\Skype\Phone
Если есть необходимость, таким же образом вносим изменения в другие переменные и жмем «ОК».
Завершаем сеанс пользователя, чтобы изменения сохранились в системе. Снова заходим в «Командную строку» и пытаемся запустить Скайп, введя
Готово! Теперь вы можете запускать любую программу, а не только Skype, находясь в любой директории в «Командной строке».
Способ 2: «Командная строка»
Рассмотрим случай, когда мы хотим установить %APPDATA% на диск «D». Эта переменная отсутствует в «Переменных среды», поэтому ее невозможно изменить первым способом.
- Чтобы узнать текущее значение переменной, в «Командной строке» введите:
В нашем случае эта папка находится по адресу:
Для того чтобы изменить ее значение, введите:
Внимание! Убедитесь, что точно знаете зачем вы это делаете, поскольку необдуманные действия могут привести к неработоспособности Виндовс.
Значение успешно изменено.
Изменение значений переменных среды требует определенных знаний в этой сфере. Не играйтесь со значениями и не редактируйте их наугад, чтобы не навредить ОС. Хорошо изучите теоретический материал, и только после этого переходите к практике.
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.