Настройка переменных среды 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
Прежде чем приступать, учтите: изменение системных переменных среды по умолчанию может привести к проблемам в работе системы, не удаляйте уже имеющиеся переменные среды. Возможно, имеет смысл создать точку восстановления системы, если вы не уверены в своих действиях.
- Чтобы открыть переменные среды Windows вы можете использовать поиск в панели задач (начните вводить «Переменных» и откройте пункт «Изменение системных переменных среды») или нажать клавиши Win+R на клавиатуре, ввести sysdm.cpl и нажать Enter.
- На вкладке «Дополнительно» нажмите кнопку «Переменные среды…»
- В разделе «Переменные среды пользователя» (если требуется изменение только для текущего пользователя) или «Системные переменные» выберите переменную, которую нужно изменить и нажмите «Изменить» (обычно требуется именно это), либо, если необходимо создать новую переменную — нажмите кнопку «Создать». В моем примере — добавляем свои пути в системную переменную Path (выбираем эту переменную и нажимаем «Изменить»).
- Для добавления нового значения (пути) в системную переменную в следующем окне можно нажать кнопку «Создать», либо просто дважды кликнуть по первой пустой строке, затем — ввести нужный путь к папке, содержащей нужные нам исполняемые файлы.
- Также вы можете использовать кнопку «Изменить текст», в этом случае окно изменения системной переменной откроется в ином виде: имя переменной, а ниже — её значение. В случае указания путей значение будет представлять собой все пути, хранящиеся в переменной, разделенные знаком «точка с запятой».
- При создании новой переменной среды окно будет тем же, что и в 5-м шаге: необходимо будет указать имя системной переменной в верхнем поле, а её значение — в нижнем.
После создания или изменения переменной среды и сохранения сделанных настроек, переменная или обновленные значения сразу становятся доступны для текущего пользователя или в системе в целом в зависимости от того, какие именно переменные редактировались или создавались. Также есть методы добавления переменных среды в командной строке или PowerShell, подробнее в статье: Как добавить путь в переменную среды PATH
If you want to see or check the names and values of Environment Variables in Windows 11 or Windows 10, here is how you can do that. There are mainly four ways to find almost everything about the Environment Variables in Windows 11/10, and this article explains all the possible methods.
What are Environment Variables in Windows 11/10
Environment Variables contain some information related to WindowsApps path, currently logged-in user’s information, Temporary folder’s path, running processes, etc. Although Windows 11/10 comes with a few of those, you can add or modify Environment Variables in Windows PC easily.
However, if you want to find those Environment Variables in Windows 11 or Windows 10, this guide will be handy for you. As said earlier, there are four ways – using the Windows Settings panel, using Command Prompt, using the Registry Editor, and using Windows PowerShell.
To see the names and values of Environment Variables in Windows 11/10, follow these methods:
- Using Windows Settings panel
- Using Command Prompt
- Using Registry Editor
- Using Windows PowerShell
To learn more about these steps, continue reading.
1] Using Windows Settings panel
It is the most common method to find the names and values of the Environment Variables in Windows 11/10 PC. Earlier, it was possible to do the same using Control Panel. However, if you are using Windows 11, there is no need to go through the Control Panel since it will eventually open the Windows Settings.
Follow these steps to find the Environment Variables:
- Press Win+I to open Windows Settings.
- Go to System > About.
- Click on the Advanced system settings.
- Click the Environment Variables button.
- Find the Environment Variables.
Next, you need to click on each variable to find the details. It displays a detailed list in the System variables box.
2] Using Command Prompt
It is probably the easiest method to find almost everything about the Environment Variables on Windows 11/10 PC. For this purpose, we are going to use the Command Prompt instance in Windows Terminal. However, you can open the standalone Command Prompt window and enter the following command:
set
In case you do not know the process to open the Windows Terminal, you can press Win+X and select the Windows Terminal from the WinX menu.
3] Using Registry Editor
If you do not want to do much with the Environment Variables and want to check them only, you can use the Registry Editor. As these variables depend on the user profile, you need to open the HKEY_CURRENT_USER. To find the names and values of the Environment Variables using Registry Editor, do the following:
- Press Win+R to open the Run prompt.
- Type regedit and hit the Enter button.
- Click on the Yes button in the UAC prompt.
- Navigate to this path: HKEY_CURRENT_USER\Environment
- Find the variables.
In case you want to modify the existing variables using Registry Editor, you need to double-click on each of them and change them according.
4] Using Windows PowerShell
Like, Command Prompt, you can use Windows PowerShell to find the same Environment Variables on your Windows 11 or Windows 10 computer. However, it displays all the Environment Variables of all the users, whereas other methods display only the current user’s variables. That being said, the list could be lengthy since it may contain some variables, such as ComSpec, LOCALAPPDATA, HOMEDRIVE, HOMEPATH, ALLUSERSPROFILE, etc.
If you are fine with the lengthy list, you can use Windows PowerShell and enter this command:
dir env:
Like the Command Prompt method, you can open the standalone Windows PowerShell or the PowerShell instance in the Windows Terminal.
How do I view Environment Variables in Windows 11?
To view the Environment Variables in Windows 11, you can use any of the aforementioned methods. If you do not want to modify existing variables, you can use the Command Prompt method. For that, you can open the Command Prompt or the Command Prompt instance in Windows Terminal and enter this command: set. Then, it displays almost everything about the current user’s Environment Variables on your screen. Similarly, you can use the Windows PowerShell method to get the same thing done. In that case, you have to use this command: dir env:
How do I get a list of Environment Variables?
To get a list of Environment Variables, you have four techniques in your hands. However, using the Windows Settings method is probably the most fruitful method since you can view, add, or modify any Environment Variable without any issue. However, if you want to get a list only, you can use any of the other three methods. To choose one, you can open the Windows Terminal and enter this command in the PowerShell instance: dir env:. If you want to use the Command Prompt instance, you need to execute this command: set.
That’s all! Hope this guide helped.
Read: How to add or edit a PATH Environment Variable in Windows.
Readers help support Windows Report. We may get a commission if you buy through our links.
Read our disclosure page to find out how can you help Windows Report sustain the editorial team. Read more
Setting environment variables on Windows 11 can help you customize your system, run scripts, and configure applications.
In this guide, we will discuss three ways with step-by-step instructions to do that so you can configure your system according to your preferences. But first:
Types of Environment Variables
There are three types of Environment Variables:
- System Environment Variables – The global variables are at the lowest priority, can be accessed by all users & apps on a Windows, and are usually used to define system-wide settings.
- User Environment Variables – With a higher priority, these only apply to the current user & processes running under that account & are set by the user or apps that run under that account.
- Process Environment Variables – With the highest priority, they are temporary and apply to the current process & its child processes, providing runtime information or customization for a program.
How do I set & use Environment Variables on Windows 11?
1. Using the Settings app
- Press Windows + I to open Settings.
- Go to System, then click About.
- Click the Advanced system settings link.
- On the System Properties window, click Environment Variables.
- Next, on the Environment Variables window, you will see two types of variables. Choose an option from either User variables for user or System variables and click New.
- On the following window, type in the Variable name without any spaces, and for Variable Value, click the Browse Directory or Browse File button.
- Select the path and click OK.
2. Using the Command Prompt
- Press the Windows key, type cmd in the search bar, and click Run as administrator.
- To add a temporary variable to your system, use this command after replacing VariableName & Variablevalue with the one you want and hit Enter:
set VariableName = Variablevalue
- The set command is used to define an environment variable within the process for which it is defined and will be deleted once the window is closed.
- To set environment variables permanently, type the following command after replacing the Variablename with the name of the variable & Value with the value you want to set and press Enter:
setx Variablename Value /m
- Now for the path variables, type the following command to list all of them and hit Enter:
echo %PATH%
- Copy & paste the following command to add another variable to the path directory; replace the PATH value with the path you want to add and press Enter:
setx PATH "%PATH%; PATH Value
- Refresh the Environment variable window to see the newly added path.
3. Using the Windows PowerShell
- Press the Windows key, type powershell, and click Run as administrator.
- Type the following command to list of path variables and press Enter: [Environment]::GetEnvironmentVariable(“PATH”)
- Copy & paste the following command to declare a path variable after replacing PATH with the path you want to add and hit Enter:
$Variable_Name = "PATH"
- To add the variable to the Path Variable list, use this command after replacing Folder PATH with the path you declared and press Enter: [Environment]::SetEnvironmentVariable(“Folder PATH”, “$PATH;$Variable_Name”)
- Restart your computer to let the changes take effect.
You can use any of the methods to add a new or missing environment variable to prevent issues like the system could not find the environment option that was entered
- Microsoft wants Windows 10 users to upgrade to Windows 11 or Copilot + PCs
- Windows 11 KB5055627 update makes File Explorer more fluid
- A few keyboard settings are moving from Control Panel to Settings app in Windows 11
- Details of Windows 11 25H2 spotted in the wild; likely to be a smaller update
How do I edit Environment Variables on Windows 11?
1. Using the Settings app
- Press Windows + I to open Settings, then go to System > About >Advanced system settings.
- Click Environment Variables, then select the variable you want to edit and click Edit.
- Make the changes and click OK on all three windows to save the changes.
- Restart the Environment Variable window to see the changes.
2. Using the Registry Editor
- Press Windows + R to open the Run dialog box.
- Type regedit and click OK to open Registry Editor.
- Navigate to this path if you are making changes to User Variables:
Computer\HKEY_CURRENT_USER\Environment
- For System Variables, go to this path:
Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
- Once you have located either of the variables, you can change the name by right-clicking and selecting Rename.
- To edit the value, double-click the variable, change the Value data, and click OK.
- Restart your computer to save the changes.
3. Using the Windows PowerShell
- Open Windows PowerShell with administrator privileges using the same steps mentioned above.
- Type the following command to get the current value of the variable after replacing VARIABLENAME with the variable name and press Enter:
$Env: VARIABLENAME
- Next, to update or edit the value, copy & paste the following command after replacing the VARIABLEANME with the name of the variable & NEWVALUE with the value that you want to add, then hit Enter:
$Env: VARIABLENAME = "NEWVALUE"
- Reboot your PC to save the changes.
How do I get a list of Environment Variables in Windows?
To get a list of environment variables in Windows 11, you can open Command Prompt with administrator rights and type set, and hit Enter.
In Powershell, with admin privileges to get a list of environment variables, copy & paste the following command and hit Enter: [System.Environment]::GetEnvironmentVariables()
If you want to print the environment variables list you got on PowerShell to apply the same settings on another computer, read this guide.
Where are Windows environment variables stored?
You can find the environment variables in Registry Editor. The system variables are found in Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment, wherein the user variables are located at Computer\HKEY_CURRENT_USER\Environment
Setting environment variables on Windows 11 can help you customize your system settings; however, you must always exercise caution when making changes to system variables.
Remember to double-check the variable name & value, and always create a backup of your registry editor before making changes.
Stuck somewhere? Don’t hesitate to mention your queries in the comments section below. We will be happy to assist you.
Srishti Sisodia
Windows Software Expert
Srishti Sisodia is an electronics engineer and writer with a passion for technology. She has extensive experience exploring the latest technological advancements and sharing her insights through informative blogs.
Her diverse interests bring a unique perspective to her work, and she approaches everything with commitment, enthusiasm, and a willingness to learn. That’s why she’s part of Windows Report’s Reviewers team, always willing to share the real-life experience with any software or hardware product. She’s also specialized in Azure, cloud computing, and AI.
This article explains how to set up environment variables in Windows 11.
Environment variables are a powerful feature in Windows systems. Various processes and applications use them to determine operational behaviors based on specific system-wide or user-specific settings.
They store configuration data and system state information that can be accessed by different software applications and services running on a Windows system.
You can customize your System’s behavior for different applications and tasks by setting up environment variables. For example, you can set a variable to specify the path to a specific tool or define a variable that controls the behavior of a specific application.
In Windows 11, environment variables can be created through System Properties, the Command Prompt, or PowerShell.
Using System Properties
To create an environment variable using System Properties, follow these steps:
Right-click the Start button and select System on the Power User menu.
Next, click the Advanced system settings link under “Related settings” on the right.
This will open the System Properties window with the Advanced tab selected. Click the Environment Variables… button at the bottom of the System Properties window.
To create a user-specific variable, under the “User variables for [Your Username]” section, click the New… button.
To create a system-wide variable (accessible to all users), under the “System variables” section, click the New… button.
In the New System Variable or New User Variable window, enter the variable’s Name and its Value.
Create User Variable:
Under the User variables for the [Username] section, click New. Then, type in the Variable name and Variable value.
Click OK to close the new variable window.
Create System Variable:
Under the System Variables section, click the New button. Then, enter the Variable name and Variable value.
Click OK again to close the Environment Variables window.
You might need to restart your System or log out and back in for some changes.
Using the Command Prompt
You can also create environment variables via Command Prompt.
First, open the Windows Terminal app as administrator. You can also right-click the Start button and select Windows Terminal (Admin).
In the Windows Terminal, open a Command Prompt tab by clicking the down arrow icon next to the new tab button and selecting Command Prompt.
Create User Variable
Type the command
setx VARIABLE_NAME "VARIABLE_VALUE"
Replace VARIABLE_NAME
with the name you wish to assign to the variable and VARIABLE_VALUE
with the actual value.
Example:
setx Downloads "C:\Users\rworl\Downloads"
Create System Variable:
Type the command
setx /M VARIABLE_NAME "VARIABLE_VALUE"
Replace VARIABLE_NAME
with the name you wish to assign to the variable and VARIABLE_VALUE
with the actual value.
Example:
setx /M Downloads "C:\Users\rworl\Downloads"
Using Windows PowerShell
You can create environment variables using Windows PowerShell.
First, open the Windows Terminal app as administrator. Right-click the Start button and select Windows Terminal (Admin) on the Power User menu.
In the Windows Terminal, open a PowerShell tab if it’s not already open by default.
Create a User Variable
For a user-specific variable, replace Machine
with User
:
[System.Environment]::SetEnvironmentVariable('VARIABLE_NAME', 'VARIABLE_VALUE', [System.EnvironmentVariableTarget]::User)
.
Example:
[Environment]::SetEnvironmentVariable("Downloads","C:\Users\Richard\Downloads","User")
Create a System Variable
Type the command
[System.Environment]::SetEnvironmentVariable('VARIABLE_NAME', 'VARIABLE_VALUE', [System.EnvironmentVariableTarget]::Machine)
Example:
[Environment]::SetEnvironmentVariable("Downloads","%UserProfile%\Downloads","Machine")
After using the command line methods, the environment variable is immediately available in new Command Prompt or PowerShe instances.
However, you may still need to restart applications or the System to see the changes everywhere.
Verifying the Creation of the Variable
To confirm that your environment variable has been set, you can use the Command Prompt or PowerShell to echo its value:
- In Command Prompt:
echo %VARIABLE_NAME%
- In PowerShell:
$env:VARIABLE_NAME
If the environment variable has been successfully created, the commands above should display its value.
That should do it!
Conclusion:
- Environment variables in Windows 11 are a powerful feature that can be used to store configuration data and system state information.
- Users can customize system behavior for applications and tasks by setting up environment variables.
- This article provides detailed steps for creating environment variables using System Properties, Command Prompt, and Windows PowerShell in Windows 11.
- After creating environment variables, users can verify their successful creation using Command Prompt or PowerShell.
- Feel free to leave a comment if you have any feedback or additional information to share regarding this guide.
Все способы:
- Переменные среды Windows
- Переменные PATH и PATHEXT
- Создание переменных среды
- Заключение
- Вопросы и ответы: 6
Переменная среды (переменная окружения) – это короткая ссылка на какой-либо объект в системе. С помощью таких сокращений, например, можно создавать универсальные пути для приложений, которые будут работать на любых ПК, независимо от имен пользователей и других параметров.
Переменные среды Windows
Получить информацию о существующих переменных можно в свойствах системы. Для этого кликаем по ярлыку Компьютера на рабочем столе правой кнопкой мыши и выбираем соответствующий пункт.
Переходим в «Дополнительные параметры».
В открывшемся окне с вкладкой «Дополнительно» нажимаем кнопку, указанную на скриншоте ниже.
Здесь мы видим два блока. Первый содержит пользовательские переменные, а второй системные.
Если требуется просмотреть весь перечень, запускаем «Командную строку» от имени администратора и выполняем команду (вводим и нажимаем ENTER).
set > %homepath%\desktop\set.txt
Подробнее: Как открыть «Командную строку» в Windows 10
На рабочем столе появится файл с названием «set.txt», в котором будут указаны все переменные окружения, имеющиеся в системе.
Все их можно использовать в консоли или скриптах для запуска программ или поиска объектов, заключив имя в знаки процента. Например, в команде выше вместо пути
C:\Users\Имя_пользователя
мы использовали
%homepath%
Примечание: регистр при написании переменных не важен. Path=path=PATH
Переменные PATH и PATHEXT
Если с обычными переменными все понятно (одна ссылка – одно значение), то эти две стоят особняком. При детальном рассмотрении видно, что они ссылаются сразу на несколько объектов. Давайте разберемся, как это работает.
«PATH» позволяет запускать исполняемые файлы и скрипты, «лежащие» в определенных каталогах, без указания их точного местоположения. Например, если ввести в «Командную строку»
explorer.exe
система осуществит поиск по папкам, указанным в значении переменной, найдет и запустит соответствующую программу. Этим можно воспользоваться в своих целях двумя способами:
- Поместить необходимый файл в одну из указанных директорий. Полный список можно получить, выделив переменную и нажав «Изменить».
- Создать свою папку в любом месте и прописать путь к ней. Для этого (после создания директории на диске) жмем «Создать», вводим адрес и ОК.
%SYSTEMROOT% определяет путь до папки «Windows» независимо от буквы диска.
Затем нажимаем ОК в окнах «Переменные среды» и «Свойства системы».
Для применения настроек, возможно, придется перезапустить «Проводник». Сделать это быстро можно так:
Открываем «Командную строку» и пишем команду
taskkill /F /IM explorer.exe
Все папки и «Панель задач» исчезнут. Далее снова запускаем «Проводник».
explorer
Еще один момент: если вы работали с «Командной строкой», ее также следует перезапустить, то есть консоль не будет «знать», что настройки изменились. Это же касается и фреймворков, в которых вы отлаживаете свой код. Также можно перезагрузить компьютер или выйти и снова зайти в систему.
Теперь все файлы, помещенные в «C:\Script» можно будет открывать (запускать), введя только их название.
«PATHEXT», в свою очередь, дает возможность не указывать даже расширение файла, если оно прописано в ее значениях.
Принцип работы следующий: система перебирает расширения по очереди, пока не будет найден соответствующий объект, причем делает это в директориях, указанных в «PATH».
Создание переменных среды
Создаются переменные просто:
- Нажимаем кнопку «Создать». Сделать это можно как в пользовательском разделе, так и в системном.
- Вводим имя, например, «desktop». Обратите внимание на то, чтобы такое название еще не было использовано (просмотрите списки).
- В поле «Значение» указываем путь до папки «Рабочий стол».
C:\Users\Имя_пользователя\Desktop
- Нажимаем ОК. Повторяем это действие во всех открытых окнах (см. выше).
- Перезапускаем «Проводник» и консоль или целиком систему.
- Готово, новая переменная создана, увидеть ее можно в соответствующем списке.
Для примера переделаем команду, которую мы использовали для получения списка (самая первая в статье). Теперь нам вместо
set > %homepath%\desktop\set.txt
потребуется ввести только
set > %desktop%\set.txt
Заключение
Использование переменных окружения позволяет значительно сэкономить время при написании скриптов или взаимодействии с системной консолью. Еще одним плюсом является оптимизация создаваемого кода. Имейте в виду, что созданные вами переменные отсутствуют на других компьютерах, и сценарии (скрипты, приложения) с их использованием работать не будут, поэтому перед тем, как передавать файлы другому пользователю, необходимо уведомить его об этом и предложить создать соответствующий элемент в своей системе.
Наша группа в TelegramПолезные советы и помощь