I want to make a backup with PostGreSQL pg_dump command with command line like :
"<c:Program FilesPostgreSQL9.6binpg_dump>" -h localhost -p 5432 -d test_backup_bat -U user -f D:destination_backuptest.backup
but I need to set PGPASSWORD before as environment variable to execute the backup command
PGPASSWORD=mypassword
How can I make this in only one command line into Windows CLI ?
asked Jul 31, 2018 at 14:57
3
Setting a variable and using it inside the same line in a batch file or a command line can be «tricky» as the full line/command is parsed before the variable is set.
BUT, in your case, you don’t need to do anything special because you don’t need to use the variable in the command except for setting it. The pg_dump
just reads the contents of the environment variable from its own environment block that is inherited from the parent cmd
process. If the parent process has the variable defined, then pg_dump
can read it from its own copy.
So, you just need two commands (one to set the variable and one to start the new process) inside the same line, executed one after the other. This is done with the &
operator:
set "PGPASSWORD=myPassword" & "c:Program FilesPostgreSQL9.6binpg_dump" -h localhost -p 5432 -d test_backup_bat -U user -f D:destination_backuptest.backup
answered Jul 31, 2018 at 15:51
MC NDMC ND
68.9k8 gold badges82 silver badges125 bronze badges
4
To Set:
SET PGPASSWORD=mypasssword
To Verify:
echo %PGPASSWORD%
KyleMit♦
36.4k63 gold badges440 silver badges635 bronze badges
answered Jul 31, 2018 at 15:11
1
Is there a way to set environment variables for a single command?
From the current cmd
shell:
You have to clear the variable yourself.
set ENVVAR=abc && dir & set ENVVAR=
From a batch file:
You can use setlocal
and endlocal
.
@echo off
setlocal
set ENVVAR=abc && dir
endlocal
Use a child cmd
shell:
You can use cmd /c
to create a child shell.
The variable is set in the child shell and doesn’t affect the parent shell (as pointed out in a comment by jpmc26).
cmd /C "set ENVVAR=abc && dir"
Further Reading
- An A-Z Index of the Windows CMD command line — An excellent reference for all things Windows cmd line related.
- cmd — Start a new CMD shell and (optionally) run a command/executable program.
- endlocal — End localisation of environment changes in a batch file. Pass variables from one batch file to another.
- redirection — Redirection operators.
- set — Display, set, or remove CMD environment variables. Changes made with SET will remain only for the duration of the current CMD session.
- setlocal — Set options to control the visibility of environment variables in a batch file.
Introduction
Environment variables are key-value pairs a system uses to set up a software environment. The environment variables also play a crucial role in certain installations, such as installing Java on your PC or Raspberry Pi.
In this tutorial, we will cover different ways you can set, list, and unset environment variables in Windows 10.
Prerequisites
- A system running Windows 10
- User account with admin privileges
- Access to the Command Prompt or Windows PowerShell
Check Current Environment Variables
The method for checking current environment variables depends on whether you are using the Command Prompt or Windows PowerShell:
List All Environment Variables
In the Command Prompt, use the following command to list all environment variables:
set
If you are using Windows PowerShell, list all the environment variables with:
Get-ChildItem Env:
Check A Specific Environment Variable
Both the Command Prompt and PowerShell use the echo
command to list specific environment variables.
The Command prompt uses the following syntax:
echo %[variable_name]%
In Windows PowerShell, use:
echo $Env:[variable_name]
Here, [variable_name]
is the name of the environment variable you want to check.
Follow the steps to set environment variables using the Windows GUI:
1. Press Windows + R to open the Windows Run prompt.
2. Type in sysdm.cpl and click OK.
3. Open the Advanced tab and click on the Environment Variables button in the System Properties window.
4. The Environment Variables window is divided into two sections. The sections display user-specific and system-wide environment variables. To add a variable, click the New… button under the appropriate section.
5. Enter the variable name and value in the New User Variable prompt and click OK.
Set Environment Variable in Windows via Command Prompt
Use the setx
command to set a new user-specific environment variable via the Command Prompt:
setx [variable_name] "[variable_value]"
Where:
[variable_name]
: The name of the environment variable you want to set.[variable_value]
: The value you want to assign to the new environment variable.
For instance:
setx Test_variable "Variable value"
Note: You need to restart the Command Prompt for the changes to take effect.
To add a system-wide environment variable, open the Command Prompt as administrator and use:
setx [variable_name] "[variable_value]" /M
Unset Environment Variables
There are two ways to unset environment variables in Windows:
Unset Environment Variables in Windows via GUI
To unset an environment variable using the GUI, follow the steps in the section on setting environment variables via GUI to reach the Environment Variables window.
In this window:
1. Locate the variable you want to unset in the appropriate section.
2. Click the variable to highlight it.
3. Click the Delete button to unset it.
Unset Environment Variables in Windows via Registry
When you add an environment variable in Windows, the key-value pair is saved in the registry. The default registry folders for environment variables are:
- user-specific variables: HKEY_CURRENT_USEREnvironment
- system-wide variables: HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment
Using the reg
command allows you to review and unset environment variables directly in the registry.
Note: The reg
command works the same in the Command Prompt and Windows PowerShell.
Use the following command to list all user-specific environment variables:
reg query HKEY_CURRENT_USEREnvironment
List all the system environment variables with:
reg query "HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment"
If you want to list a specific variable, use:
reg query HKEY_CURRENT_USEREnvironment /v [variable_name]
or
reg query "HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment" /v [variable_name]
Where:
/v
: Declares the intent to list a specific variable.[variable_name]
: The name of the environment variable you want to list.
Use the following command to unset an environment variable in the registry:
reg delete HKEY_CURRENT_USEREnvironment /v [variable_name] /f
or
reg delete "HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment" /v [variable_name] /f
Note: The /f
parameter is used to confirm the reg delete
command. Without it, entering the command triggers the Delete the registry value EXAMPLE (Yes/No)?
prompt.
Run the setx
command again to propagate the environment variables and confirm the changes to the registry.
Note: If you don’t have any other variables to add with the setx
command, set a throwaway variable. For example:
setx [variable_name] trash
Conclusion
After following this guide, you should know how to set user-specific and system-wide environment variables in Windows 10.
Looking for this tutorial for a different OS? Check out our guides on How to Set Environment Variables in Linux and How to Set Environment Variables in MacOS.
Переменная среды (environment variable) — текстовая короткая ссылка на элемент операционной системы Windows, предназначенная для получения быстрого доступа к объекту системы, или к данным о каталогах и конфигурации компьютера. Переменная среды (переменная окружения) позволяет быстро перейти к нужному месту на компьютере, без использования имени пользователя или полного пути к объекту.
Переменные окружения Windows используются в командной строке, в диалоговом окне «Выполнить» и адресной строке Проводника. Переменная среды может содержать информацию о настройках системы или данные о текущем пользователе компьютера.
Содержание:
- Пример использования переменной среды Windows
- Как посмотреть переменные среды Windows 10
- Доступ к переменным средам из реестра Windows
- Как посмотреть все переменные среды в командной строке
- Открытие списка переменных среды в Windows PowerShell
- Создание переменной среды в Windows
- Список переменных среды Windows в таблице
- Выводы статьи
Переменные среды Windows делятся на два вида:
- Пользовательские переменные среды — содержат указания пути к пользовательским каталогам.
- Системные переменные среды — содержат информацию о каталогах ОС и конфигурации ПК.
Чаще всего переменные среды используются как путь к дискам, файлам или параметрам системы. Использование переменной среды позволяет быстро перейти к нужной директории операционной системы, без ввода полного пути, например, без ввода имени пользователя.
Переменные окружения часто используются при написании скриптов, или при работе в командной строке. Короткие переменные можно использовать вместо полного пути до файла или папки, например, при создании ярлыков, при вводе пути к объекту.
Пример использования переменной среды Windows
Рассмотрим следующий пример: пользователю нужно открыть системную папку «AppData», в которой находятся различные данные программ, установленных в операционную систему Windows. Скрытая папка «AppData» находится в профиле пользователя, обычно на диске «C:». Данные приложений расположены по пути:
C:UsersИмя_ пользователяAppDataRoaming
Чтобы получить доступ к этой папке нужно выполнить несколько последовательных действий: открыть Проводник, включить в Windows отображение скрытых папок и файлов, а затем пройти по всему пути до нужной папки.
При помощи переменной «%APPDATA%» (переменная используется без кавычек) можно сразу открыть нужную директорию в системе, без ввода имени пользователя, включения отображения скрытых папок, ввода полного пути. Это экономит много времени.
Чтобы открыть нужный каталог достаточно лишь ввести «%APPDATA%» в поле поиска Windows, в адресную строку Проводника или в диалоговое окно «Выполнить», а затем нажать на клавишу «Enter».
Переменные среды Виндовс заключены в специальный оператор «%», который находится с двух сторон названия переменной. Это необходимо, чтобы система могла обработать запрос.
Пользователь может самостоятельно создавать переменные среды или изменять существующие. В статье мы рассмотрим несколько способов просмотра переменных среды и самостоятельное создание переменной. В руководстве вы найдете таблицу со списком переменных, применяемых в операционных системах Windows 10, Windows 8.1, Windows 8, Windows 7.
Как посмотреть переменные среды Windows 10
Сейчас мы посмотрим, как получить доступ к переменным средам в операционной системе Windows 10. В других версиях Windows необходимо выполнить аналогичные действия.
Чтобы посмотреть переменные окружения Windows 10, выполните следующее:
- Нажмите на клавиши» «Win» + «R».
- В окне «Выполнить» введите команду: «systempropertiesadvanced» (без кавычек), а затем нажмите на кнопку «ОК».
- В окне «Свойства системы», во вкладке «Дополнительно» нажмите на кнопку «Переменные среды…».
- В окне «Переменные среды» отображаются пользовательские переменные среды и системные переменные среды.
Доступ к переменным средам из реестра Windows
Есть возможность получить доступ к переменным средам из системного реестра Windows. Пользователю нужно будет открыть редактор реестра, а затем пройти по пути до определенной ветки.
Системные переменные среды находятся по следующему пути:
HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment
Переменные среды локального пользователя расположены в следующей ветке реестра:
HKEY_CURRENT_USEREnvironment
Вы можете создать в редакторе реестра новые переменные или изменить существующие.
Как посмотреть все переменные среды в командной строке
Пользователь может получить список переменных среды при помощи системного инструмента — командной строки Windows.
В cmd переменные среды открываются следующим образом:
- Запустите командную строку от имени администратора.
- Выполните команду:
set
Для получения списка переменных в виде текстового файла, выполните в командной строке команду:
set > C:Variables.txt
После выполнения этой команды, на Локальном диске «C:» появится текстовый файл с именем «Variables» (имя можно использовать любое), в котором находится список переменных среды Windows.
На моем компьютере файл имеет следующее содержание:
ALLUSERSPROFILE=C:ProgramData APPDATA=C:UsersUserAppDataRoaming CommonProgramFiles=C:Program FilesCommon Files CommonProgramFiles(x86)=C:Program Files (x86)Common Files CommonProgramW6432=C:Program FilesCommon Files COMPUTERNAME=DESKTOP-3HEECRJ ComSpec=C:WINDOWSsystem32cmd.exe DokanLibrary1=C:Program FilesDokanDokanLibrary-1.2.2 DriverData=C:WindowsSystem32DriversDriverData HOMEDRIVE=C: HOMEPATH=UsersUser LOCALAPPDATA=C:UsersUserAppDataLocal LOGONSERVER=\DESKTOP-3HEECRJ NUMBER_OF_PROCESSORS=4 OneDrive=C:UsersUserOneDrive OneDriveConsumer=C:UsersUserOneDrive OS=Windows_NT Path=C:Program Files (x86)Common FilesOracleJavajavapath;C:Windowssystem32;C:Windows;C:WindowsSystem32Wbem;C:WindowsSystem32WindowsPowerShellv1.0;C:WindowsSystem32OpenSSH;C:Program Files (x86)NVIDIA CorporationPhysXCommon;C:WINDOWSsystem32;C:WINDOWS;C:WINDOWSSystem32Wbem;C:WINDOWSSystem32WindowsPowerShellv1.0;C:WINDOWSSystem32OpenSSH;C:Program Files (x86)Windows LiveShared;C:Program FilesNVIDIA CorporationNVIDIA NvDLISR;C:WINDOWSsystem32;C:WINDOWS;C:WINDOWSSystem32Wbem;C:WINDOWSSystem32WindowsPowerShellv1.0;C:WINDOWSSystem32OpenSSH;C:UsersUserAppDataLocalMicrosoftWindowsApps PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC PROCESSOR_ARCHITECTURE=AMD64 PROCESSOR_IDENTIFIER=Intel64 Family 6 Model 60 Stepping 3, GenuineIntel PROCESSOR_LEVEL=6 PROCESSOR_REVISION=3c03 ProgramData=C:ProgramData ProgramFiles=C:Program Files ProgramFiles(x86)=C:Program Files (x86) ProgramW6432=C:Program Files PROMPT=$P$G PSModulePath=C:Program FilesWindowsPowerShellModules;C:WINDOWSsystem32WindowsPowerShellv1.0Modules PUBLIC=C:UsersPublic SystemDrive=C: SystemRoot=C:WINDOWS TEMP=C:UsersUserAppDataLocalTemp TMP=C:UsersUserAppDataLocalTemp TMPDIR=C:UsersPublicDocumentsWondershareCreatorTemp USERDOMAIN=DESKTOP-3HEECRJ USERDOMAIN_ROAMINGPROFILE=DESKTOP-3HEECRJ USERNAME=User USERPROFILE=C:UsersUser windir=C:WINDOWS
Открытие списка переменных среды в Windows PowerShell
Открытие списка переменных среды возможно при помощи системного средства Windows PowerShell.
Выполните следующие действия:
- Запустите Windows PowerShell от имени администратора.
- Введите команду, а затем нажмите на клавишу «Enter»:
dir Env:
- В окне PowerShell откроется список переменных среды Windows.
Создание переменной среды в Windows
Пользователь может самостоятельно создать новую переменную для открытия директорий на компьютере, или для запуска программ.
Перед внесением изменений в переменные окружения, обратите внимание на то, что бездумное изменение значений переменных среды Windows может привести к сбоям или неполадкам в работе операционной системы.
Проделайте следующее:
- В окне «Переменные среды» выберите одну из групп переменных: пользовательские или системные переменные.
- Нажмите на кнопку «Создать…».
На этом примере я создам отдельную переменную среды для запуска программы TeamViewer.
- В окне «Изменение пользовательской переменной» добавьте имя переменной, а в поле «Значение переменной:» введите полный путь к исполняемому файлу.
- В окне переменных сред добавилась новая переменная. Нажмите на кнопку «ОК» для применения изменений.
- В диалоговом окне «Выполнить» введите «%Имя_переменной%», в нашем случае, «%TeamViewer%», нажмите на кнопку «ОК».
- На Рабочем столе компьютера откроется окно запущенной программы.
Подобным способом, после ввода переменной в адресную строку Проводника, выполняется запуск программы или открытие директории на ПК.
Переменная среды пути «Path» содержит список директорий на компьютере, в которых система должна искать исполняемые файлы. Переменная среды пути «PATH» не добавляется к исполняемым файлам, а только к директориям, где находятся данные файлы.
Если добавить в переменную среды Path Windows путь к директории с исполняемым файлом, например, для браузера Google Chrome: C:Program Files (x86)GoogleChromeApplication
, то программа запустится из командной строки, после выполнения команды «chrome», без ввода полного пути к исполняемому файлу.
При необходимости, пользователь может удалить ненужную переменную из операционной системы Windows.
Список переменных среды Windows в таблице
Для удобства посетителей сайта я собрал в общую таблицу переменные, их описание и значения в операционной системе Windows. В подавляющем большинстве случаев, системная папка расположена на диске «C:», поэтому пути в значениях даны для этого диска.
Переменная | Назначение | Значение переменной |
---|---|---|
%ALLUSERSPROFILE% | Папка ProgramData | C:ProgramData |
%APPDATA% | Папка размещения данных программ | C:UsersUserAppDataRoaming |
%CommonProgramFiles% | Папка Common Files в Program Files | C:Program FilesCommon Files |
%CommonProgramW6432% | Папка Common Files в Program Files | C:Program FilesCommon Files |
%COMPUTERNAME% | Имя компьютера | DESKTOP-XXXXXXX |
%ComSpec% | Запуск командной строки | C:WINDOWSsystem32cmd.exe |
%DriverData% | Папка DriverData | C:WindowsSystem32DriversDriverData |
%HOMEDRIVE% | Системный диск | C: |
%HOMEPATH% | Папка профиля пользователя | C:UsersUser |
%LOCALAPPDATA% | Папка локальных данных приложений | C:UsersUserAppDataLocal |
%LOGONSERVER% | Имя контроллера домена | DESKTOP-XXXXXXX |
%NUMBER_OF_PROCESSORS% | Количество потоков процессора | |
%OneDrive% | Папка OneDrive | C:UsersUserOneDrive |
%Path% | Путь поиска исполняемых файлов | C:Windowssystem32;C:Windows;C:WindowsSystem32Wbem;… |
%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 FilesWindowsPowerShellModules;C:WINDOWSsystem32WindowsPowerShellv1.0Modules |
%PUBLIC% | Папка «Общие» в профиле пользователей | C:UsersPublic |
%SystemDrive% | Системный диск с Windows | C: |
%SystemRoot% | Папка Windows | C:Windows |
%TEMP% | Временный каталог | C:UsersUserAppDataLocalTemp |
%TMP% | Временный каталог | C:UsersUserAppDataLocalTemp |
%USERDOMAIN% | Имя домена | DESKTOP-XXXXXXX |
%USERNAME% | Имя пользователя | User |
%USERPROFILE% | Профиль пользователя | C:UsersUser |
%Windir% | Папка Windows | C:Windows |
Выводы статьи
Переменные окружения Windows позволяют пользователю экономить время во время работы на компьютере. Переменными средами Windows могут пользоваться обычные пользователи или системные администраторы для быстрого доступа к объектам операционной системы, чтобы открыть нужную директорию на компьютере, или запустить программу.
Похожие публикации:
- Некоторыми параметрами управляет ваша организация в Windows 10
- Как закрепить папку на панели задач Windows 10 — 5 способов
- Как создать загрузочную флешку Windows 7 — 5 способов
- Как удалить программу в Windows 10 — 9 способов
- Оптимизация Windows 10 для ускорения работы ПК
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.
Print environment variables
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:
Command Prompt
List all environment variables
Command Prompt — C:>
Output
1
2
3
4
5
6
ALLUSERSPROFILE=C:ProgramData
APPDATA=C:UsersuserAppDataRoaming
.
.
.
windir=C:Windows
Print a particular environment variable:
Command Prompt — C:>
Output
Windows PowerShell
List all environment variables
Windows PowerShell — PS C:>
Output
1
2
3
4
5
6
7
8
Name Value
---- -----
ALLUSERSPROFILE C:ProgramData
APPDATA C:UsersuserAppDataRoaming
.
.
.
windir C:Windows
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:>
1
setx EC2_CERT "%USERPROFILE%awscert.pem"
Open a new command prompt.
Command Prompt — C:>
Output
1
C:Usersuserawscert.pem
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:>
1
setx EC2_HOME "%APPDATA%awsec2-api-tools" /M
Warning This method is recommended for experienced users only.
The location of the user variables in the registry is: HKEY_CURRENT_USEREnvironment
. The location of the system variables in the registry is: HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment
.
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.
First we’ll show the user variables:
Command Prompt — C:>
1
reg query HKEY_CURRENT_USEREnvironment
Output
1
2
3
HKEY_CURRENT_USEREnvironment
TEMP REG_EXPAND_SZ %USERPROFILE%AppDataLocalTemp
TMP REG_EXPAND_SZ %USERPROFILE%AppDataLocalTemp
We can show a specific environment variable by adding /v
then the name, in this case we’ll do TEMP
:
Command Prompt — C:>
1
reg query HKEY_CURRENT_USEREnvironment /v TEMP
Output
1
2
HKEY_CURRENT_USEREnvironment
TEMP REG_EXPAND_SZ %USERPROFILE%AppDataLocalTemp
Now we’ll list the system environment variables:
Command Prompt — C:>
1
reg query "HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment"
Output
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment
ComSpec REG_EXPAND_SZ %SystemRoot%system32cmd.exe
FP_NO_HOST_CHECK REG_SZ NO
NUMBER_OF_PROCESSORS REG_SZ 8
OS REG_SZ Windows_NT
Path REG_EXPAND_SZ C:ProgramDataOracleJavajavapath;C:WINDOWSsystem32;C:WINDOWS;C:WINDOWSSystem32Wbem;C:WINDOWSSystem32WindowsPowerShellv1.0;%SystemRoot%system32;%SystemRoot%;%SystemRoot%System32Wbem;%SYSTEMROOT%System32WindowsPowerShellv1.0
PATHEXT REG_SZ .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
PROCESSOR_ARCHITECTURE REG_SZ AMD64
PROCESSOR_IDENTIFIER REG_SZ Intel64 Family 6 Model 60 Stepping 3, GenuineIntel
PROCESSOR_LEVEL REG_SZ 6
PROCESSOR_REVISION REG_SZ 3c03
PSModulePath REG_EXPAND_SZ %SystemRoot%system32WindowsPowerShellv1.0Modules;C:Program FilesIntel
TEMP REG_EXPAND_SZ %SystemRoot%TEMP
TMP REG_EXPAND_SZ %SystemRoot%TEMP
USERNAME REG_SZ SYSTEM
windir REG_EXPAND_SZ %SystemRoot%
And same as with the user variables we can query a specific variable.
Command Prompt — C:>
1
reg query "HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment" /v PATH
Output
1
2
HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment
PATH REG_EXPAND_SZ C:ProgramDataOracleJavajavapath;C:WINDOWSsystem32;C:WINDOWS;C:WINDOWSSystem32Wbem;C:WINDOWSSystem32WindowsPowerShellv1.0;%SystemRoot%system32;%SystemRoot%;%SystemRoot%System32Wbem;%SYSTEMROOT%System32WindowsPowerShellv1.0
Unsetting a Variable
When setting environment variables on the command line, setx
should be used because then the environment variables will be propagated appropriately. However one notable thing setx
doesn’t do is unset environment variables. The reg
tool can take care of that, however another setx
command should be run afterwards to propagate the environment variables.
The layout for deleting a user variable is: reg delete HKEY_CURRENT_USEREnvironment /v variable_name /f
. If /f
had been left off, we would have been prompted: Delete the registry value EXAMPLE (Yes/No)?
. For this example we’ll delete the user variable USER_EXAMPLE
:
Command Prompt — C:>
1
reg delete HKEY_CURRENT_USEREnvironment /v USER_EXAMPLE /f
Output
1
The operation completed successfully.
Deleting a system variable requires administrator privileges. See HowTo: Open an Administrator Command Prompt in Windows to see how to do this.
The layout for deleting a system variable is: reg delete "HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment" /v variable_name /f
. For this example we’ll delete the system variable SYSTEM_EXAMPLE
:
Command Prompt — C:>
1
reg delete "HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment" /v SYSTEM_EXAMPLE /f
If this was run as a normal user you’ll get:
Output
1
ERROR: Access is denied.
But run in an administrator shell will give us:
Output
1
The operation completed successfully.
Finally we’ll have to run a setx
command to propagate the environment variables. If there were other variables to set, we could just do that now. However if we were just interested in unsetting variables, we will need to have one variable left behind. In this case we’ll set a user variable named throwaway
with a value of trash
Command Prompt — C:>
Output
1
SUCCESS: Specified value was saved.
Resources
- Windows XP Service Pack 2 Support Tools
- Windows Server 2003 Resource Kit Tools
- Reg — Edit Registry | Windows CMD | SS64.com
- Reg — Microsoft TechNet
- Registry Value Types (Windows) — Microsoft Windows Dev Center
- How to propagate environment variables to the system — Microsoft Support
- WM_SETTINGCHANGE message (Windows) — Microsoft Windows Dev Center
- Environment Variables (Windows) — Microsoft Windows Dev Center
Windows Server 2003 Resource Kit Tools will also work with Windows XP and Windows XP SP1; use Windows XP Service Pack 2 Support Tools with Windows XP SP2. Neither download is supported on 64-bit version.
Parts in this series
- HowTo: Set an Environment Variable in Windows
- HowTo: Set an Environment Variable in Windows — GUI
- HowTo: Set an Environment Variable in Windows — Command Line and Registry
What is an environment variable in Windows? An environment variable is a dynamic “object” containing an editable value which may be used by one or more software programs in Windows.
In this note i am showing how to set an environment variable in Windows from the command-line prompt (CMD) and from the Windows PowerShell.
In the examples below i will set an environment variable temporary (for the current terminal session only), permanently for the current user and globally for the whole system.
Cool Tip: Add a directory to Windows %PATH%
environment variable! Read More →
Set Environment Variable For The Current Session
Set an environment variable for the current terminal session:
# Windows CMD C:> set VAR_NAME="VALUE" # Windows PowerShell PS C:> $env:VAR_NAME="VALUE"
Print an environment variable to the console:
# Windows CMD C:> echo %VAR_NAME% # Windows PowerShell PS C:> $env:VAR_NAME
Cool Tip: List Windows environment variables and their values! Read More →
Set Environment Variable Permanently
Run as Administrator: The setx
command is only available starting from Windows 7 and requires elevated command prompt. It works both for the Windows command-line prompt (CMD) and the Windows PowerShell.
Permanently set an environment variable for the current user:
C:> setx VAR_NAME "VALUE"
Permanently set global environment variable (for all users):
C:> setx /M VAR_NAME "VALUE"
Info: To see the changes after running setx
– open a new command prompt.
It is easy to add or modify an environment variable with Command Prompt (CMD), but removing one is much more complicated. Here are a few different ways you can do it.
How to Add or Modify an Environment Variable
First, you need to launch Command Prompt, or CMD, as an administrator. Click Start, type “cmd” into the search box, and then click “Run as Administrator.”
Note: Any user environment variable can be set or modified in a regular Command Prompt window, but changing system-wide environment variables requires an elevated Command Prompt.
There are two distinct ways to set environment variables.
Setting an Environment Variable Temporarily
The first uses the set command. Set defines an environment variable exclusively within the process in which it has been defined — in other words, the variable only works in the window you have open or the script that contains it.
Here’s an example: Let’s say you want to create an environment variable named LifeAnswerVar and set the value to 42. The command would be set LifeAnswerVar=42
.
While that window is open, LifeAnswerVar will have the value 42.
When it is closed, the environment variable and its value are deleted.
The exact same method works if you want to temporarily modify an existing Windows system variable. All you need to do is substitute the system variable you want to change in place of LifeAnswerVar, and the value you want to assign in place of 42.
As an example, if you wanted to move the TMP folder to C:Example Folder, you’d enter the command set TMP=C:"Example Folder"
.
The first line, set TMP
, shows the current value of TMP. The second line assigns TMP a new value. The third line confirms that it has changed.
Setting an Environment Variable Permanently
The second way uses setx. Setx defines Windows environment variables permanently. They persist between windows and between restarts, and are written to the Windows Registry. These environment variables can be defined for a specific user, or they can be defined for system-wide use.
The command setx ExVar1 Tomato /m
will create a new environment variable named ExVar1 and assign the value “Tomato” to it. The /m argument specifies that the new variable should be system-wide, not just for the current user.
Use the exact same command to modify an existing environment variable, substituting ExVar1 for the name of the variable you’d like to change.
Note: If you use setx to modify a variable and set to view the value of the variable, set will not display the right value until a new Command Prompt window is opened.
If you want to add or modify a user environment variable, just omit the /m argument from the command.
How to Remove an Environment Variable
Removing an environment variable is a bit harder than adding or modifying one.
Note: As with adding a variable, any user environment variable can be deleted in a regular Command Prompt window, but deleting a system-wide environment variable requires an elevated Command Prompt.
Removing an Environment Variable Temporarily
If you want to temporarily remove an environment variable for the current process, like a script, PowerShell window, or Command Prompt window, you can use the set command. All you need to do is assign no value to the variable.
For example, what if you have the variable definition ExVar1=Tomato
in the system-wide environment variables, but wanted to ignore it for one particular process? You can type set ExVar1=
into Command Prompt or include that line in your script. The variable will be set to nothing while the script executes or until you open a new Command Prompt window.
Removing an Environment Variable Permanently
Removing an environment variable permanently is a bit more complex — you have to use reg
to do it.
Warning: Reg is the command-line version of the Registry Editor. You should proceed with caution — a typo could result in you accidentally deleting something important. It never hurts to back up the part of the registry you’re editing, either.
The environment variables for individual users are stored in HKEY_CURRENT_USEREnvironment
. System-wide environment variables are stored elsewhere, in HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment
.
Let’s use the ExVar1=Tomato
example. The ExVar1 environment variable was defined system-wide, which means it is located in the HKEY_LOCAL_MACHINE directory rather than the HKEY_CURRENT_USER directory. Specifically, the path to the subkey is:
HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironmentExVar1
Note: This path contains a space. Any time there is a space in a path entered in a command-line interface, you must use quotation marks around the path, otherwise, it is exceedingly likely that it will not execute correctly.
Now we need to use the reg delete
command to remove it. Keep in mind that you’ll need to substitute your variable name for ExVar1 in the command below.
reg delete "HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment" /f /v ExVar1
There is a lot there, so let’s break it down a bit.
- reg delete — defines the application (reg) and command (delete) we’re using
"HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment"
— Tells reg delete where to look for the key- /f — Tells reg delete to delete the key without prompting for confirmation
- /v — Tells reg delete that it will be given a specific subkey to delete
- ExVar1 — The name of the subkey we want to delete
Deleting an environment variable for an individual user is exactly the same as deleting a system-wide variable, except the path will be different. If ExVar1 were a user environment variable, the command to delete it would be:
reg delete HKEY_CURRENT_USEREnvironment /f /v ExVar1
If the command to delete the environment variable was successful, you should see “The operation completed successfully” in the Command Prompt.
Any time you remove an environment variable like this, you need to restart explorer.exe. You can restart Explorer.exe manually, or you can just restart your entire computer. Either will work, and the changes should take effect immediately after the restart.
RELATED: How to List Environment Variables on Linux
READ NEXT
- › How to Check Your Java Version on Windows 11
- › How to Change Your Age on TikTok
- › The New HP Pro x360 Fortis Is a 2-In-1 Laptop Under $500
- › This Huge Curved Ultrawide Monitor From LG Is $337 Today
- › How to Screen Record on iPhone
- › Get PC Power With Tablet Portability in the Surface Pro 9 for $200 Off
- › PSA: You Can Email Books and Documents to Your Kindle
Windows environment variables are very important, it plays an important role in Windows OS. This article will tell you how to set windows environment variables both on GUI and command line.
1. Set Windows Environment Variables On GUI.
- Open a Windows Explorer, right-click This-PC on the left side, then click the Properties menu item in the popup menu list, then it will popup the System window.
- Click the Advanced system settings item in the popup window left side, it will popup the System Properties window.
- Click the Environment Variables… button at the bottom-right of the System Properties window, it will popup the Environment Variables window.
- There are two parts in the Environment Variables dialog. The upper part area is the User variables ( only available to this user ) list, the lower part area is the System variables ( available to all users that use this Windows OS ) list.
- Click the New… button to add a new environment variable, input variable name ( such as CLASSPATH), and variable value ( such as C: ) in the popup dialog, click the OK button to save it.
- To edit a windows environment variable, just select it and click the Edit… button. For example, we select the system variable Path and click the Edit… button, then you can add a new path value or edit the existing path value in the popup dialog.
- The variable name is just a string, and if one environment variable has multiple values, you should use
;
to separate them.
2. Set Windows Environment Variables In Command-Line.
If you want to get and set windows environment variables in a shell script, you had better use the command line to process it.
2.1 Print Windows Environment Variables In Command-Line.
- Run the command
set
in the Dos window to show current environment variables.C:WorkSpace>set ALLUSERSPROFILE=C:ProgramData ...... OS=Windows_NT Path=C:Program Files (x86)Common FilesOracleJavajavapath;C:Windowssystem32;C:Windows;C:WindowsSystem32Wbem;C:WindowsSystem32WindowsPowerShellv1.0; ......
- Run the command
echo %variable-name%
in the Dos window to print the special environment variable value.C:WorkSpace>echo %PATH% C:Program Files (x86)Common FilesOracleJavajavapath;C:Windowssystem32;C:Windows;C:WindowsSystem32Wbem;
- Run command
Get-ChildItem Env:
in the Windows PowerShell window to print all environment variables.PS C:Userssong zhao> Get-ChildItem Env: Name Value ---- ----- ALLUSERSPROFILE C:ProgramData APPDATA C:Userssong zhaoAppDataRoaming CommonProgramFiles C:Program FilesCommon Files
- Run command
echo $Env:variable-name
in Windows PowerShell window to print special environment variable value.PS C:Userssong zhao> echo $Env:PATH C:Program Files (x86)Common FilesOracleJavajavapath;
2.2 Set Windows Environment Variables In Command-Line.
- We can run
setx
command in both Dos window and Windows PowerShell to set environment variables in the command line. The command format issetx variable-name variable-value
.C:WorkSpace>setx HELLO 'haha' SUCCESS: Specified value was saved. ------------------------------------------- PS C:Userssong zhao> setx ABC "C:" SUCCESS: Specified value was saved.
- If the user environment variable does not exist, then it will add a new one. If the user environment variable name already exists, then it will overwrite it.
- To see the changes, you need to open a new Dos window or PowerShell window and run the command
echo %HELLO%
orecho %ABC%
.C:Userssong zhao>echo %HELLO% 'haha' C:Userssong zhao>echo %ABC% C:
- If you want to set a system environment variable, you should first run Dos window or PowerShell window as administrator and then run the command
setx variable-name variable-value /M
, otherwise, you will encounter the error message ERROR: Access to the registry path is denied. - In the below example, we use windows GUI to add a system environment variable TEST_VAR first, then we want to overwrite it in the command line. Because the Dos window is not opened as administrator, then an error message is thrown.
PS C:Userssong zhao> setx TEST_VAR "C:" /M ERROR: Access to the registry path is denied.
We can also set environment variables in Windows registry, we will introduce it later in this article.