Windows view environment variables

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.

About Environment Variables

SHORT DESCRIPTION

Describes how to access Windows environment variables in PowerShell.

LONG DESCRIPTION

Environment variables store information about the operating system environment. This information includes details such as the operating system path, the number of processors used by the operating system, and the location of temporary folders.

The environment variables store data that is used by the operating system and other programs. For example, the WINDIR environment variable contains the location of the Windows installation directory. Programs can query the value of this variable to determine where Windows operating system files are located.

PowerShell can access and manage environment variables in any of the supported operating system platforms. The PowerShell environment provider simplifies this process by making it easy to view and change environment variables.

Environment variables, unlike other types of variables in PowerShell, are inherited by child processes, such as local background jobs and the sessions in which module members run. This makes environment variables well suited to storing values that are needed in both parent and child processes.

Using and changing environment variables

On Windows, environment variables can be defined in three scopes:

  • Machine (or System) scope
  • User scope
  • Process scope

The Process scope contains the environment variables available in the current process, or PowerShell session. This list of variables is inherited from the parent process and is constructed from the variables in the Machine and User scopes. Unix-based platforms only have the Process scope.

Читайте также:  Не работает правый shift windows

You can display and change the values of environment variables without using a cmdlet by using a variable syntax with the environment provider. To display the value of an environment variable, use the following syntax:

For example, to display the value of the WINDIR environment variable, type the following command at the PowerShell command prompt:

In this syntax, the dollar sign ( $ ) indicates a variable, and the drive name ( Env: ) indicates an environment variable followed by the variable name ( windir ).

When you change environment variables in PowerShell, the change affects only the current session. This behavior resembles the behavior of the Set command in the Windows Command Shell and the Setenv command in UNIX-based environments. To change values in the Machine or User scopes, you must use the methods of the System.Environment class.

To make changes to Machine-scoped variables, must also have permission. If you try to change a value without sufficient permission, the command fails and PowerShell displays an error.

You can change the values of variables without using a cmdlet using the following syntax:

For example, to append ;c:\temp to the value of the Path environment variable, use the following syntax:

On Linux or MacOS, the colon ( : ) in the command separates the new path from the path that precedes it in the list.

You can also use the Item cmdlets, such as Set-Item , Remove-Item , and Copy-Item to change the values of environment variables. For example, to use the Set-Item cmdlet to append ;c:\temp to the value of the Path environment variable, use the following syntax:

In this command, the value is enclosed in parentheses so that it is interpreted as a unit.

Environment variables that store preferences

PowerShell features can use environment variables to store user preferences. These variables work like preference variables, but they are inherited by child sessions of the sessions in which they are created. For more information about preference variables, see about_preference_variables.

The environment variables that store preferences include:

Stores the execution policy set for the current session. This environment variable exists only when you set an execution policy for a single session. You can do this in two different ways.

Start a session from the command line using the ExecutionPolicy parameter to set the execution policy for the session.

Use the Set-ExecutionPolicy cmdlet. Use the Scope parameter with a value of «Process».

PowerShell provides control over the file that is used to cache data about modules and their cmdlets. The cache is read at startup while searching for a command and is written on a background thread sometime after a module is imported.

Default location of the cache is:

  • Windows PowerShell 5.1: $env:LOCALAPPDATA\Microsoft\Windows\PowerShell
  • PowerShell 6.0 and higher: $env:LOCALAPPDATA\Microsoft\PowerShell
  • Non-Windows default:

The default filename for the cache is ModuleAnalysisCache . When you have multiple instances of PowerShell installed, the filename includes a hexadecimal suffix so that there is a a unique filename per installation.

If command discovery isn’t working correctly, for example Intellisense shows commands that don’t exist, you can delete the cache file. The cache is recreated the next time you start PowerShell.

To change the default location of the cache, set the environment variable before starting PowerShell. Changes to this environment variable only affect child processes. The value should name a full path (including filename) that PowerShell has permission to create and write files.

To disable the file cache, set this value to an invalid location, for example:

This sets the path to the NUL device. PowerShell can’t write to the path but no error is returned. You can see the errors reported using a tracer:

When writing out the module analysis cache, PowerShell checks for modules that no longer exist to avoid an unnecessarily large cache. Sometimes these checks are not desirable, in which case you can turn them off by setting this environment variable value to 1 .

Setting this environment variable takes effect immediately in the current process.

The $env:PSModulePath environment variable contains a list of folder locations that are searched to find modules and resources.

By default, the effective locations assigned to $env:PSModulePath are:

System-wide locations: These folders contain modules that ship with PowerShell. The modules are store in the $PSHOME\Modules location. Also, This is the location where the Windows management modules are installed.

User-installed modules: These are modules installed by the user. Install-Module has a Scope parameter that allows you to specify whether the module is installed for the current user or for all users. For more information, see Install-Module.

  • On Windows, the location of the user-specific CurrentUser scope is the $HOME\Documents\PowerShell\Modules folder. The location of the AllUsers scope is $env:ProgramFiles\PowerShell\Modules .
  • On non-Windows systems, the location of the user-specific CurrentUser scope is the $HOME/.local/share/powershell/Modules folder. The location of the AllUsers scope is /usr/local/share/powershell/Modules .
Читайте также:  Windows 10 pro x64 20h2 msdn

In addition, setup programs that install modules in other directories, such as the Program Files directory, can append their locations to the value of $env:PSModulePath .

For more information, see about_PSModulePath.

Managing environment variables

PowerShell provides several different methods for managing environment variables.

  • The Environment provider drive
  • The Item cmdlets
  • The .NET System.Environment class
  • On Windows, the System Control Panel

Using the Environment provider

Each environment variable is represented by an instance of the System.Collections.DictionaryEntry class. In each DictionaryEntry object, the name of the environment variable is the dictionary key. The value of the variable is the dictionary value.

To display the properties and methods of the object that represents an environment variable in PowerShell, use the Get-Member cmdlet. For example, to display the methods and properties of all the objects in the Env: drive, type:

The PowerShell Environment provider lets you access environment variables in a PowerShell drive (the Env: drive). This drive looks much like a file system drive. To go to the Env: drive, type:

Use the Content cmdlets to get or set the values of an environment variable.

You can view the environment variables in the Env: drive from any other PowerShell drive, and you can go into the Env: drive to view and change the environment variables.

Using Item cmdlets

When you refer to an environment variable, type the Env: drive name followed by the name of the variable. For example, to display the value of the COMPUTERNAME environment variable, type:

To display the values of all the environment variables, type:

Because environment variables do not have child items, the output of Get-Item and Get-ChildItem is the same.

By default, PowerShell displays the environment variables in the order in which it retrieves them. To sort the list of environment variables by variable name, pipe the output of a Get-ChildItem command to the Sort-Object cmdlet. For example, from any PowerShell drive, type:

You can also go into the Env: drive by using the Set-Location cmdlet:

When you are in the Env: drive, you can omit the Env: drive name from the path. For example, to display all the environment variables, type:

To display the value of the COMPUTERNAME variable from within the Env: drive, type:

Saving changes to environment variables

To make a persistent change to an environment variable on Windows, use the System Control Panel. Select Advanced System Settings. On the Advanced tab, click Environment Variable. . You can add or edit existing environment variables in the User and System (Machine) scopes. Windows writes these values to the Registry so that they persist across sessions and system restarts.

Alternately, you can add or change environment variables in your PowerShell profile. This method works for any version of PowerShell on any supported platform.

Читайте также:  Windows затер загрузчик linux

Using System.Environment methods

The System.Environment class provides GetEnvironmentVariable and SetEnvironmentVariable methods that allow you to specify the scope of the variable.

The following example uses the GetEnvironmentVariable method to get the machine setting of PSModulePath and the SetEnvironmentVariable method to add the C:\Program Files\Fabrikam\Modules path to the value.

Изучаем переменные среды в Windows 10

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

taskkill /F /IM explorer.exe

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

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

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

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

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

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

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

    Нажимаем кнопку «Создать». Сделать это можно как в пользовательском разделе, так и в системном.


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


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


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

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

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

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

    Заключение

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

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