Check the environment variable in windows

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

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.

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 (=).

Читайте также:  Драйвера canon lbp3010b linux

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.

Environment. Get Environment Variable Метод

Определение

Получение значения переменной среды. Retrieves the value of an environment variable.

Перегрузки

Возвращает из текущего процесса значение переменной среды. Retrieves the value of an environment variable from the current process.

Возвращает из текущего процесса или раздела реестра операционной системы Windows значение переменной среды для текущего пользователя или локального компьютера. Retrieves the value of an environment variable from the current process or from the Windows operating system registry key for the current user or local machine.

GetEnvironmentVariable(String)

Возвращает из текущего процесса значение переменной среды. Retrieves the value of an environment variable from the current process.

Параметры

Имя переменной среды. The name of the environment variable.

Возвращаемое значение

Значение переменной среды, заданное параметром variable или значение null , если переменная среды не найдена. The value of the environment variable specified by variable , or null if the environment variable is not found.

Исключения

variable имеет значение null . variable is null .

У вызывающего объекта отсутствует необходимое разрешение для выполнения этой операции. The caller does not have the required permission to perform this operation.

Примеры

В следующем примере метод используется GetEnvironmentVariable для получения windir переменной среды, которая содержит путь к каталогу Windows. The following example uses the GetEnvironmentVariable method to retrieve the windir environment variable, which contains the path of the Windows directory.

В следующем примере предпринимается попытка получить значение переменной среды с именем Test1 из блока Process окружения. The following example attempts to retrieve the value of an environment variable named Test1 from the process environment block. Если переменная не существует, в примере создается и извлекается ее значение. If the variable doesn’t exist, the example creates its and retrieves its value. В примере отображается значение переменной. The example displays the value of the variable. Если в примере создается переменная, она также вызывает GetEnvironmentVariables(EnvironmentVariableTarget) метод с каждым членом EnvironmentVariableTarget перечисления, чтобы определить, что переменную можно извлечь только из текущего блока среды процесса. If the example created the variable, it also calls the GetEnvironmentVariables(EnvironmentVariableTarget) method with each member of the EnvironmentVariableTarget enumeration to establish that the variable can be retrieved only from the current process environment block. Наконец, если в примере создается переменная, она удаляет ее. Finally, if the example created the variable, it deletes it.

Читайте также:  Mac os change date terminal

Комментарии

GetEnvironmentVariable(String)Метод получает переменную среды из блока среды только текущего процесса. The GetEnvironmentVariable(String) method retrieves an environment variable from the environment block of the current process only. Он эквивалентен вызову GetEnvironmentVariable(String, EnvironmentVariableTarget) метода со target значением EnvironmentVariableTarget.Process . It is equivalent to calling the GetEnvironmentVariable(String, EnvironmentVariableTarget) method with a target value of EnvironmentVariableTarget.Process.

Чтобы получить все переменные среды вместе со значениями, вызовите GetEnvironmentVariables метод. To retrieve all environment variables along with their values, call the GetEnvironmentVariables method.

В именах переменных среды учитывается регистр в Linux и macOS, но регистр в Windows не учитывается. Environment variable names are case-sensitive on Linux and macOS but are not case-sensitive on Windows.

В системах Windows On Windows systems

В системах Windows блок среды текущего процесса включает: On Windows systems, the environment block of the current process includes:

Все переменные среды, предоставленные ей родительским процессом, который ее создал. All environment variables that are provided to it by the parent process that created it. Например, приложение .NET, запускаемое из окна консоли, наследует все переменные среды окна консоли. For example, a .NET application launched from a console window inherits all of the console window’s environment variables.

Если родительский процесс отсутствует, вместо него используются переменные среды для компьютера и для отдельных пользователей. If there is no parent process, per-machine and per-user environment variables are used instead. Например, новое окно консоли содержит все переменные среды для каждого компьютера и пользователя, определенные на момент запуска. For example, a new console window has all per-machine and per-user environment variables defined at the time it was launched.

Любые переменные, добавляемые в блок Process во время выполнения процесса, вызывая SetEnvironmentVariable(String, String) метод или SetEnvironmentVariable(String, String, EnvironmentVariableTarget) метод со target значением EnvironmentVariableTarget.Process . Any variables added to the process block while the process is running by calling either the SetEnvironmentVariable(String, String) method or the SetEnvironmentVariable(String, String, EnvironmentVariableTarget) method with a target value of EnvironmentVariableTarget.Process. Эти переменные среды сохраняются до завершения работы приложения .NET. These environment variables persist until the .NET application terminates.

Если переменные среды создаются после запуска процесса, этот метод можно использовать для извлечения только тех переменных, которые были созданы путем вызова SetEnvironmentVariable(String, String) метода или SetEnvironmentVariable(String, String, EnvironmentVariableTarget) метода со target значением. EnvironmentVariableTarget.Process If environment variables are created after the process has started, you can use this method to retrieve only those variables that were created by calling the SetEnvironmentVariable(String, String) method or the SetEnvironmentVariable(String, String, EnvironmentVariableTarget) method with a target value of .EnvironmentVariableTarget.Process.

В системах macOS и Linux On macOS and Linux systems

В macOS и Linux блок среды текущего процесса включает следующие переменные среды: On macOS and Linux, the environment block of the current process includes the following environment variables:

Все переменные среды, предоставленные ей родительским процессом, который ее создал. All environment variables that are provided to it by the parent process that created it. Для приложений .NET, запускаемых из оболочки, сюда входят все переменные среды, определенные в оболочке. For .NET applications launched from a shell, this includes all environment variables defined in the shell.

Любые переменные, добавляемые в блок Process во время выполнения процесса, вызывая SetEnvironmentVariable(String, String) метод или SetEnvironmentVariable(String, String, EnvironmentVariableTarget) метод со target значением EnvironmentVariableTarget.Process . Any variables added to the process block while the process is running by calling either the SetEnvironmentVariable(String, String) method or the SetEnvironmentVariable(String, String, EnvironmentVariableTarget) method with a target value of EnvironmentVariableTarget.Process. Эти переменные среды сохраняются до завершения работы приложения .NET. These environment variables persist until the .NET application terminates.

.NET Core в macOS и Linux не поддерживает переменные среды для каждого компьютера или пользователя. .NET Core on macOS and Linux does not support per-machine or per-user environment variables.

См. также раздел

Применяется к

GetEnvironmentVariable(String, EnvironmentVariableTarget)

Возвращает из текущего процесса или раздела реестра операционной системы Windows значение переменной среды для текущего пользователя или локального компьютера. Retrieves the value of an environment variable from the current process or from the Windows operating system registry key for the current user or local machine.

Читайте также:  Wipe disk in linux

Параметры

Имя переменной среды. The name of an environment variable.

Одно из значений перечисления EnvironmentVariableTarget. One of the EnvironmentVariableTarget values. На платформе .NET Core, работающей в системах UNIX, поддерживается только Process. Only Process is supported on .NET Core running on Unix-bases systems.

Возвращаемое значение

Значение переменной среды, заданное параметрами variable и target или значение null , если переменная среды не найдена. The value of the environment variable specified by the variable and target parameters, or null if the environment variable is not found.

Исключения

variable имеет значение null . variable is null .

target не является допустимым значением EnvironmentVariableTarget. target is not a valid EnvironmentVariableTarget value.

У вызывающего объекта отсутствует необходимое разрешение для выполнения этой операции. The caller does not have the required permission to perform this operation.

Примеры

В следующем примере создаются переменные среды для EnvironmentVariableTarget.Process EnvironmentVariableTarget.User целевых объектов, и Machine , проверяет, содержит ли реестр операционной системы переменные среды пользователя и компьютера, а затем удаляет переменные среды. The following example creates environment variables for the EnvironmentVariableTarget.Process, EnvironmentVariableTarget.User, and Machine targets, checks whether the operating system registry contains the user and machine environment variables, then deletes the environment variables. Так как .NET в системах на базе UNIX не поддерживает переменные среды пользователя и компьютера, только SetEnvironmentVariable(String, String) и SetEnvironmentVariable(String, String, EnvironmentVariableTarget) со значением EnvironmentVariableTarget.Process успешно сохраняет переменную среды в блоке среды Process. Because .NET on Unix-based systems does not support per-user and per-machine environment variables, only SetEnvironmentVariable(String, String) and SetEnvironmentVariable(String, String, EnvironmentVariableTarget) with a value of EnvironmentVariableTarget.Process successfully store an environment variable to the process environment block.

Комментарии

Чтобы получить все переменные среды вместе со значениями, вызовите GetEnvironmentVariables метод. To retrieve all environment variables along with their values, call the GetEnvironmentVariables method.

В именах переменных среды учитывается регистр в Linux и macOS, но регистр в Windows не учитывается. Environment variable names are case-sensitive on Linux and macOS but are not case-sensitive on Windows.

В системах Windows On Windows systems

В Windows target параметр указывает, извлекается ли переменная среды из текущего процесса или из раздела реестра операционной системы Windows для текущего пользователя или локального компьютера. On Windows, the target parameter specifies whether the environment variable is retrieved from the current process or from the Windows operating system registry key for the current user or local machine. Все переменные среды на уровне пользователя и на уровне компьютера автоматически копируются в блок среды текущего процесса, как и любые другие переменные среды, доступные для родительского процесса, создавшего процесс .NET. All per-user and per-machine environment variables are automatically copied into the environment block of the current process, as are any other environment variables that are available to the parent process that created the .NET process. Тем не менее переменные среды добавляются только в блок среды текущего процесса путем вызова SetEnvironmentVariable(String, String) метода или SetEnvironmentVariable(String, String, EnvironmentVariableTarget) метода со target значением EnvironmentVariableTarget.Process Persist только в течение процесса. However, environment variables added only to the environment block of the current process by calling either the SetEnvironmentVariable(String, String) method or the SetEnvironmentVariable(String, String, EnvironmentVariableTarget) method with a target value of EnvironmentVariableTarget.Process persist only for the duration of the process.

В системах macOS и Linux On macOS and Linux systems

В macOS и Linux GetEnvironmentVariable(String, EnvironmentVariableTarget) метод поддерживает target EnvironmentVariableTarget.Process только значение. On macOS and Linux, the GetEnvironmentVariable(String, EnvironmentVariableTarget) method supports a target value of EnvironmentVariableTarget.Process only. Вызовы со target значением EnvironmentVariableTarget.Machine или EnvironmentVariableTarget.User не поддерживаются и возвращают значение null . Calls with a target value of EnvironmentVariableTarget.Machine or EnvironmentVariableTarget.User are not supported and return null .

Переменные среды для каждого процесса: Per-process environment variables are:

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