Windows echo all environment variables

How-to: Windows Environment Variables

Environment variables are mainly used within batch files, they can be created, modified and deleted for a session using the SET command. To make permanent changes, use SETX

Variables can be displayed using either SET or ECHO.

Variables have a percent sign on both sides: %ThisIsAVariable%
The variable name can include spaces, punctuation and mixed case: %_Another Ex.ample%
(This is unlike Parameter variables which only have one % sign and are always one character long: %A )

A variable name may include any of the following characters:
A-Z, a-z, 0-9, # $ ‘ ( ) * + , — . ? @ [ ] _ `

The first character of the name must not be numeric.

Array variables

Unlike PowerShell, which fully supports arrays, there is no built in support for array variables within the CMD shell. However with some effort you can replicate this functionality using a series of separate variables, named to represent the array:

Set elem[1]=First element
Set elem[2]=Second one
Set elem[3]=The third one

To perform array indexing operations with these, use EnableDelayedExpansion and a reference like !elem[%var%]!
this is explained fully in this StackOverflow Q/A.

Standard (built-in) Environment Variables

Variable Volatile
(Read-Only)
Default value assuming the system drive is C:
ALLUSERSPROFILE C:\ProgramData
APPDATA C:\Users\ \AppData\Roaming
CD Y The current directory (string).
ClientName Y Terminal servers only — the ComputerName of a remote host.
CMDEXTVERSION Y The current Command Processor Extensions version number. (NT = «1», Win2000+ = «2».)
CMDCMDLINE Y The original command line that invoked the Command Processor.
CommonProgramFiles C:\Program Files\Common Files
COMMONPROGRAMFILES(x86) C:\Program Files (x86)\Common Files
COMPUTERNAME
COMSPEC C:\Windows\System32\cmd.exe or if running a 32 bit WOW — C:\Windows\SysWOW64\cmd.exe
DATE Y The current date using same region specific format as DATE.
ERRORLEVEL Y The current ERRORLEVEL value, automatically set when a program exits.
FPS_BROWSER_APP_PROFILE_STRING
FPS_BROWSER_USER_PROFILE_STRING
Internet Explorer
Default
These are undocumented variables for the Edge browser in Windows 10. HighestNumaNodeNumber Y (hidden) The highest NUMA node number on this computer. HOMEDRIVE Y C: HOMEPATH Y \Users\ LOCALAPPDATA C:\Users\ \AppData\Local LOGONSERVER \\ NUMBER_OF_PROCESSORS Y The Number of processors running on the machine. OS Y Operating system on the user’s workstation. PATH User and
System C:\Windows\System32\;C:\Windows\;C:\Windows\System32\Wbem; PATHEXT .COM; .EXE; .BAT; .CMD; .VBS; .VBE; .JS ; .WSF; .WSH; .MSC
Determine the default executable file extensions to search for and use, and in which order, left to right.
The syntax is like the PATH variable — semicolon separators. PROCESSOR_ARCHITECTURE Y AMD64/IA64/x86 This doesn’t tell you the architecture of the processor but only of the current process, so it returns «x86» for a 32 bit WOW process running on 64 bit Windows. See detecting OS 32/64 bit PROCESSOR_ARCHITEW6432 = %PROCESSOR_ARCHITECTURE% (but only available to 64 bit processes) PROCESSOR_IDENTIFIER Y Processor ID of the user’s workstation. PROCESSOR_LEVEL Y Processor level of the user’s workstation. PROCESSOR_REVISION Y Processor version of the user’s workstation. ProgramW6432 = %ProgramFiles% (but only available when running under a 64 bit OS) ProgramData C:\ProgramData ProgramFiles C:\Program Files or C:\Program Files (x86) ProgramFiles(x86) 1 C:\Program Files (x86) (but only available when running under a 64 bit OS) PROMPT Code for current command prompt format,usually $P$G
C:> PSModulePath %SystemRoot%\system32\WindowsPowerShell\v1.0\Modules\ Public C:\Users\Public RANDOM Y A random integer number, anything from 0 to 32,767 (inclusive). %SessionName% Terminal servers only — for a terminal server session, SessionName is a combination of the connection name, followed by #SessionNumber. For a console session, SessionName returns «Console». SYSTEMDRIVE C: SYSTEMROOT By default, Windows is installed to C:\Windows but there’s no guarantee of that, Windows can be installed to a different folder, or a different drive letter.
systemroot is a read-only system variable that will resolve to the correct location.
Defaults in early Windows versions are C:\WINNT, C:\WINNT35 and C:\WTSRV TEMP and TMP User Variable C:\Users\ \AppData\Local\Temp
Under XP this was \ \Local Settings\Temp TIME Y The current time using same format as TIME. UserDnsDomain Y
User Variable Set if a user is a logged on to a domain and returns the fully qualified DNS domain that the currently logged on user’s account belongs to. USERDOMAIN USERDOMAIN_roamingprofile The user domain for RDS or standard roaming profile paths. Windows 8/10/2012 (or Windows 7/2008 with Q2664408) USERNAME USERPROFILE %SystemDrive%\Users\
This is equivalent to the $HOME environment variable in Unix/Linux WINDIR

%windir% is a regular User variable and can be changed, which makes it less robust than %SystemRoot%
Set by default as windir=%SystemRoot%
%WinDir% pre-dates Windows NT, its use in many places has been replaced by the system variable: %SystemRoot%

1 Only on 64 bit systems, is used to store 32 bit programs.

Unless stated otherwise, all the variables above are System variables

Environment variables are stored in the registry:

User Variables: HKEY_CURRENT_USER\Environment
System Variables: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment

By default, files stored under Local Settings do not roam with a roaming profile.

Dynamic environment variables are read-only and are computed each time the variable is expanded. When all variables are listed with SET, these will not appear in the list. Do not attempt to directly SET a dynamic variable.

Shell variables

Variables for current shell session are created with the SET command and are available only to the current CMD shell. These are only stored in memory not the registry. Shell variables are destroyed when the current shell (CMD) exits.

Running the SET command with no options will display all shell variables but also all User and System environment variables.

If the SET command is used to modify the PATH, or if it is removed completely with PATH ; that will not affect any other programs or CMD sessions opened before or after the current one.

Undocumented Dynamic variables (read only)

%__APPDIR__% The directory path to the current application .exe, terminated with a trailing backslash. (Global) — discuss
%__CD__% The current directory, terminated with a trailing backslash. (Global)
%=C:% The current directory of the C: drive. ( See Raymond Chen’s explanation of this.)
%=D:% The current directory of the D: drive if drive D: has been accessed in the current CMD session.
%DPATH% Related to the (deprecated) DPATH command.
%=ExitCode% The most recent exit code returned by an external command, such as CMD /C EXIT n, converted to hex.
%=ExitCodeAscii% The most recent exit code returned by an external command, as ASCII. (Values 0-32 do not display because those map to ASCII control codes.)
%FIRMWARE_TYPE% The boot type of the system: Legacy, UEFI, Not implemented, Unknown Windows 8/2012.
%KEYS% Related to the (deprecated) KEYS command.
More detail on these undocumented variables can be found in this stackoverflow answer from Dave Benham.

Undocumented Dynamic variables (read/write)

%__COMPAT_LAYER% Set the ExecutionLevel to either RunAsInvoker (asInvoker), RunAsHighest (highestAvailable) or RunAsAdmin (requireAdministrator) for more see elevation and Q286705 / Application Compatibility Toolkit for other Compatibility Layers (colours,themes etc).

Pass variables between batch scripts

There are several ways to pass values between batch files, or between a batch file and the command line, see the CALL and SETLOCAL pages for full details.

A child process by default inherits a copy of all environment variables from its parent, this makes environment variables unsuitable for storing secret information such as API keys or user passwords, especially in rare occasions like crashes where a crash log will often include the full OS environment at the time of the crash. PowerShell/Get-Credential is a more secure approach.

If Command Extensions are disabled, the following dynamic variables will be not accessible:
%CD% %DATE% %TIME% %RANDOM% %ERRORLEVEL% %CMDEXTVERSION% %CMDCMDLINE% %HIGHESTNUMANODENUMBER%

“Men may be convinced, but they cannot be pleased against their will. But though taste is obstinate, it is very variable, and time often prevails when arguments have failed”

How the environment-building process works — Raymond Chen [MSFT].
PowerShell — Working with Environment variables.
User Shell Folders — Profile, Start Menu — Location of user profile folders.
Detecting 32 vs 64 bit Windows
CALL — Evaluate environment variables.
SET — View environment variables, set local variables.
SETX — Set environment variables.
Q100843 — The four types of environment variable.
Q286705 — Set compatibility variables in a batch file.
Q242557 — Registry Settings for Folder Redirection.
StackOverflow — Storing a Newline in a variable.

Переменные среды в 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.

Как посмотреть переменные среды 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 могут пользоваться обычные пользователи или системные администраторы для быстрого доступа к объектам операционной системы, чтобы открыть нужную директорию на компьютере, или запустить программу.

Читайте также:  Журнал dhcp сервера windows
Оцените статью