Как установить переменную среды в windows 10 cmd

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.

How to set environment variables in Windows

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
List all environment variables using the Command Prompt

If you are using Windows PowerShell, list all the environment variables with:

Get-ChildItem Env:
List all environment variables using Windows PowerShell

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]%
Checking a specific environment variable using the Command Prompt

In Windows PowerShell, use:

echo $Env:[variable_name]
Checking a specific environment variable using Windows PowerShell

Here, [variable_name] is the name of the environment variable you want to check.

Set Environment Variable in Windows via GUI

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.

Find the Environment Variables button in the Advanced tab

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.

Click on the New... button to add a variable

5. Enter the variable name and value in the New User Variable prompt and click OK.

Enter the new variable name and value

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"
Setting a user-specific environment variable via the Command Prompt

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
Setting a system environment variable via the Command Prompt

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 GUI

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
Listing all user-specific environment variables in the registry

List all the system environment variables with:

reg query "HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment"
Listing all system environment variables in the registry

If you want to list a specific variable, use:

reg query HKEY_CURRENT_USEREnvironment /v [variable_name]
Listing a specific user environment variable in the registry

or

reg query "HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment" /v [variable_name]
Listing a specific system environment variable in the registry

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
Unsetting a user-specific environment variable from the registry

or

reg delete "HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment" /v [variable_name] /f
Unsetting a system environment variable from the registry

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, How to Set Environment Variables in ZSH, and How to Set Environment Variables in MacOS.

Was this article helpful?

YesNo

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

В этой пошаговой инструкции базовая информация о том, как открыть переменные среды Windows 11 и Windows 10, создать или отредактировать их.

Что такое переменные среды

Переменные среды в Windows — записи о расположении системных папок, свойствах системы и другие, которые доступны для любой программы или скрипта.

Одна из наиболее часто используемых переменных среды — PATH, указывающая на папки, в которых выполняется поиск файлов, вызываемых в командной строке, терминале Windows, файле bat или из других источников. В качестве примера её назначения:

  • Если вы откроете командную строку (или диалоговое окно «Выполнить»), введёте regedit и нажмете Enter — вы сможете запустить редактор реестра, не указывая полный путь к файлу regedit.exe, поскольку путь C:\Windows добавлен в переменную среды Path.
  • Если же тем же образом в командной строке написать имя программы, путь к которой не добавлен в Path (chrome.exe, adb.exe, pip и другие), вы получите сообщение «Не является внутренней или внешней командой, исполняемой программой или пакетным файлом».

Если предположить, что вы часто используете команды adb.exe (например, для установки приложений Android в Windows 11), pip install (для установки пакетов Python) или любые другие то для того, чтобы не писать каждый раз полный путь к этим файлам, имеет смысл добавить эти пути в переменные среды.

Также вы можете добавлять и иные переменные среды (не обязательно содержащие пути), а в дальнейшем получать и использовать их значения в сценариях BAT (командной строки) или PowerShell. Пример получения и отображения значения системной переменной PATH для обоих случаев:

echo %PATH%
echo $Env:PATH

Получить список всех переменных среды в командной строке и PowerShell соответственно можно следующими командами:

set
ls env:

Редактирование переменных среды Windows 11/10

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

  1. Чтобы открыть переменные среды Windows вы можете использовать поиск в панели задач (начните вводить «Переменных» и откройте пункт «Изменение системных переменных среды») или нажать клавиши Win+R на клавиатуре, ввести sysdm.cpl и нажать Enter.
    Открыть изменение переменных среды в Windows

  2. На вкладке «Дополнительно» нажмите кнопку «Переменные среды…»
    Переменные среды в параметрах системы Windows

  3. В разделе «Переменные среды пользователя» (если требуется изменение только для текущего пользователя) или «Системные переменные» выберите переменную, которую нужно изменить и нажмите «Изменить» (обычно требуется именно это), либо, если необходимо создать новую переменную — нажмите кнопку «Создать». В моем примере — добавляем свои пути в системную переменную Path (выбираем эту переменную и нажимаем «Изменить»).
    Создание и изменение переменных среды Windows

  4. Для добавления нового значения (пути) в системную переменную в следующем окне можно нажать кнопку «Создать», либо просто дважды кликнуть по первой пустой строке, затем — ввести нужный путь к папке, содержащей нужные нам исполняемые файлы.
    Изменение переменно PATH

  5. Также вы можете использовать кнопку «Изменить текст», в этом случае окно изменения системной переменной откроется в ином виде: имя переменной, а ниже — её значение. В случае указания путей значение будет представлять собой все пути, хранящиеся в переменной, разделенные знаком «точка с запятой».
    Изменение имени и значения системной переменной среды

  6. При создании новой переменной среды окно будет тем же, что и в 5-м шаге: необходимо будет указать имя системной переменной в верхнем поле, а её значение — в нижнем.

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

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.

Was it useful? Share this post with the world!

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:\Users\user\AppData\Roaming
.
.
.
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:\Users\user\AppData\Roaming
.
.
.
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%\aws\cert.pem"

Open a new command prompt.

Command Prompt — C:\>

Output

1
C:\Users\user\aws\cert.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%\aws\ec2-api-tools" /M

Warning This method is recommended for experienced users only.

The location of the user variables in the registry is: HKEY_CURRENT_USER\Environment. The location of the system variables in the registry is: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment.

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_USER\Environment

Output

1
2
3
HKEY_CURRENT_USER\Environment
    TEMP    REG_EXPAND_SZ    %USERPROFILE%\AppData\Local\Temp
    TMP    REG_EXPAND_SZ    %USERPROFILE%\AppData\Local\Temp

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_USER\Environment /v TEMP

Output

1
2
HKEY_CURRENT_USER\Environment
    TEMP    REG_EXPAND_SZ    %USERPROFILE%\AppData\Local\Temp

Now we’ll list the system environment variables:

Command Prompt — C:\>

1
reg query "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"

Output

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
    ComSpec    REG_EXPAND_SZ    %SystemRoot%\system32\cmd.exe
    FP_NO_HOST_CHECK    REG_SZ    NO
    NUMBER_OF_PROCESSORS    REG_SZ    8
    OS    REG_SZ    Windows_NT
    Path    REG_EXPAND_SZ    C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.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%\system32\WindowsPowerShell\v1.0\Modules\;C:\Program Files\Intel\
    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_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v PATH

Output

1
2
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
    PATH    REG_EXPAND_SZ    C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.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_USER\Environment /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_USER\Environment /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_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v variable_name /f. For this example we’ll delete the system variable SYSTEM_EXAMPLE:

Command Prompt — C:\>

1
reg delete "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /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

Windows 10 supports a number of legacy features from older versions of the operating system. One of those legacy features is the environment variable. Environment variables offer a useful way to control the way Windows operates with an extremely small footprint in terms of memory usage.

For example, one common environment variable is called PATH, which is simply an ordered text string containing a list of directories that Windows should look in when an executable file is called. The PATH environment variable allows users to quickly launch programs without having to know where those programs live on the hard drive.

Setting environment variables is very useful and, fortunately, very simple. In this article, we’ll go over how to find and set your environment variables in Windows 10.

  1. Once logged in to Windows, right-click the Windows button in the lower-left corner of your screen and click System from the Power User Task Menu that’s displayed on the screen.
  2. Under the System menu, you need to click the Advanced System Settings.
    • If you can’t find Advanced System Settings there, type “advanced system settings” into the search box and hit return to bring it up.
  3. Once Advanced System Settings is open, click on the Advanced tab, then look on the bottom-right side for the Environment Variables.
    System Properties

  4. Next, to create a new environment variable, click New. You might need to make a System variable depending upon what you’re doing.

  5. A dialog box will pop up, allowing you to enter a new variable name and to set its initial value:
    • New adds a new environment variable.
    • Edit lets you edit whatever environment variable you have selected.
    • Delete lets you delete the selected environment variable.
  6. Save any changes that you make by clicking OK.

How to Find the PATH Variable in Windows 10

  1. Under the Environment Variables window, choose or highlight the PATH variable in the System Variables section shown in the window.

  2. After highlighting the PATH variable from System Variables, click the Edit button.
  3. You can add or modify the path lines with the directories you want your computer to look in for executable files.
    • You will find that each different directory is separated with a semicolon, for example: C:Program Files;C:Winnt;C:WinntSystem32
  4. There are other environment variables in the System Variables section that you can examine by clicking Edit.
  5. Likewise, there are different environment variables, such as PATH, HOME, USER PROFILE, HOME and APP DATA, TERM, PS1, MAIL, TEMP, and so on. These Windows environment variables are very useful and can be used in scripts as well as on the command line.
  6. Once finished, you can test your changes by opening a new PowerShell window and entering the following: $env:PATH

Frequently Asked Questions

Here is some more information about Environment Variables for you:

How Do I Find Environment Variables in Windows 10?

To find environment variables in Windows 10, you can follow the steps described above to find the environment variable information tucked away inside the system’s advanced settings.

Alternatively, if you just need to see what the variables are but don’t need to change them, you can simply open a command-line interface by hitting Ctrl +Esc and typing “cmd” in the command box, then type “set” in the command window. This prints out all the environment variables that are set on your system.

Why Can’t I Edit the Environment Variables?

There are several reasons that you may not be able to set these variables.

1. The first of your problems could be that you don’t have Admin rights. To set or edit this function, you must be the Administrator of the system.

2. If you are the Admin, yet the edit function is greyed out, try accessing the Environment Variables by accessing the Control Panel from the Start menu. Click on Advanced System Settings, then click Environment Variables.

Final Thoughts

Windows 10 environment variables make it incredibly easy to take control of your Windows device and make it run more efficiently. To find and set environment variables in Windows 10, follow the simple steps laid out in this article to get started.

Disclaimer: Some pages on this site may include an affiliate link. This does not effect our editorial in any way.

Send To Someone

Missing Device

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как сделать автоматический набор номера windows 10
  • Как скрыть windows defender из панели задач
  • Если подключить жесткий диск к другому компьютеру будет ли работать windows
  • Как удалить windows defender в windows 10 навсегда powershell
  • How to uninstall python windows