Настройка переменных среды 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
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.
In Windows 11, the environment variables (env) can be easily set via the graphical user interface. The ENV on Windows or other operating-system needed by it to let it know exactly where the most important files are stored. And that can be a little different on every computer. For most Windows users, the system is located in the C:\Windows\ folder and programs in the C:\Program Files\folder. But it is not always the case.
Add or Display system variables Path in Windows 111. Open Edit system environment variables2. System Properties3. Add System Variables or User Variable on Windows 114. Create a New Variable and add the path in Windows 11
And this is the reason why the paths are important locations, they are not permanently programmed, but are stored in so-called environment variables.
There are also environment variables that do not lead to any folders. These are variables like Dirverdata, PATHEXT, and more…
Environment variables are an important element of every operating system, including Windows 11. But how do you actually get them?
Add or Display system variables Path in Windows 11
1. Open Edit system environment variables
For this, you simply use the Windows 11 search and search for “Edit system environment variables“. Then simply select the result and the following window with the system properties will open.
2. System Properties
You will see the “System Properties” there click on the “Environment Variables …” button, which is already focused on in the given screenshot.
3. Add System Variables or User Variable on Windows 11
On the Environment Variable windows you will have two choices:
- User variables for your account; the folder path added under it will only be accessible by that particular user
- System variables for the entire operating system, hence any user account will be able to access the executables or folder declared under it.
Added System variables are visible to all user accounts. If it is the case that only you use the PC, it is sufficient to set user variables. However, here we are going for “System Variables“. You can choose between as per your choice.
Select the Path and hit the Edit button.
4. Create a New Variable and add the path in Windows 11
As you click the Edit button in the above step, the corresponding window will open. After that add the path of the folder or executable that you want to add.
Alternatively, we can also browse the same.
For example, to integrate the Oracle VirtualBox, simply edit the “Path” variable under the system or user variables. So follow the below steps…
• Select the Path variable, click on Edit … and click on Browse
• A file explorer tree will open, go to the folder that you want to add, and hit the OK button.
Then confirm all windows with OK and restart the command line (Windows Terminal/PowerShell/Command Prompt) and start accessing your executable directly in it once. The old variables are still saved in the open instance.
In this way, we can add any path to our system on Windows 11 using the graphical user interface. the user can also remove any of the added paths in a similar way.
System variables are essential components of the Windows operating system that provide information about various settings and system paths. Being able to edit system variables allows users to customize their system environment, add new paths, and modify existing variables to suit their needs. In this blog post, we will explore different methods to edit system variables on Windows 11, enabling users to enhance their computing experience and optimize their system’s performance.
Video Tutorial:
What’s Needed
To successfully edit system variables on Windows 11, you will need administrative access to your computer and a basic understanding of the Windows operating system. Additionally, having a clear idea of the variables you want to modify or add will be helpful. It is also recommended to create a backup of your system before making any changes to avoid any unforeseen issues.
What Requires Your Focus?
When editing system variables on Windows 11, there are a few key factors that require your attention. Firstly, you need to identify the variable you want to modify or add. This could be a system variable already present or a new variable that you want to create. Secondly, you should familiarize yourself with the potential implications of modifying a system variable. Incorrect changes to certain variables can impact the functioning of your system or specific applications. Lastly, you need to ensure that you have administrative privileges to make changes to system variables.
Method 1: Using the Control Panel
Editing system variables through the Control Panel is a straightforward method that provides a user-friendly interface for making changes. Before proceeding, ensure that you have administrative access to your Windows 11 computer.
1. Open the Control Panel by typing «Control Panel» in the Windows search bar and selecting the corresponding result.
2. In the Control Panel, navigate to the «System and Security» category.
3. Click on «System» to open the System Properties window.
4. In the System Properties window, click on the «Advanced system settings» link from the left-hand side menu.
5. In the System Properties dialog box, click on the «Environment Variables» button.
6. In the Environment Variables dialog box, you will see two sections: User variables and System variables.
7. To edit a variable, select it from the appropriate section and click on the «Edit» button.
8. Make the necessary changes to the variable’s value and click «OK» to save the changes.
9. To add a new variable, click on the «New» button in the corresponding section, enter the variable name and value, and click «OK» to save.
Pros | Cons |
---|---|
1. User-friendly interface for editing system variables. | 1. Limited control over advanced settings and options. |
2. Provides a visual representation of existing variables. | 2. May not be suitable for users who prefer command-line interfaces. |
3. Easy to navigate and locate specific variables. | 3. May require administrative access for certain changes. |
Method 2: Via the Windows 11 Settings
Windows 11 settings offer an alternative method for editing system variables. This method does not require accessing the Control Panel and provides a modern, streamlined user interface.
1. Open the Windows 11 Settings by pressing the Windows key + I on your keyboard or clicking the Start button and selecting the Settings icon.
2. In the Settings window, click on the «System» category.
3. From the left-hand side menu, select «About.«
4. Scroll down to the bottom of the About page and click on the «Advanced system settings» link.
5. The System Properties dialog box will open, similar to Method 1.
6. Proceed with steps 6 to 9 mentioned in Method 1 to edit or add system variables.
Pros | Cons |
---|---|
1. Integrated within the Windows 11 settings, providing a unified experience. | 1. Limited advanced options compared to the Control Panel method. |
2. Modern and intuitive user interface. | 2. May not be suitable for users who prefer a command-line interface. |
3. Easily accessible from the main Windows 11 settings. | 3. May require administrative access for certain changes. |
Method 3: Using the Command Prompt
For users who prefer a command-line interface or need more advanced options, editing system variables through the Command Prompt is a powerful alternative.
1. Open the Command Prompt by typing «Command Prompt» in the Windows search bar, right-clicking on the app’s icon, and selecting «Run as administrator.«
2. In the Command Prompt window, type «setx VARIABLE_NAME «VALUE«» and press Enter.
3. Replace VARIABLE_NAME with the name of the variable you want to modify or add.
4. Replace VALUE with the desired value for the variable.
5. Press Enter to execute the command.
6. You will receive a confirmation message indicating whether the command was executed successfully.
Pros | Cons |
---|---|
1. Provides advanced options and capabilities compared to graphical interfaces. | 1. Requires familiarity with command-line interface and commands. |
2. Allows for batch processing and script automation. | 2. Limited visual representation of existing variables. |
3. Offers fine-grained control over system variable modifications. | 3. May not be suitable for users who prefer graphical interfaces. |
Method 4: Using the Registry Editor
Editing system variables through the Windows Registry Editor provides a more advanced approach and should only be attempted by experienced users who are familiar with the Windows Registry.
1. Open the Registry Editor by typing «regedit» in the Windows search bar and selecting the corresponding result.
2. In the Registry Editor window, navigate to the following path: «HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment«
3. In the right-hand side pane, you will see a list of variables and their values.
4. To modify a variable, double-click on it and edit the value data.
5. To add a new variable, right-click on the empty space in the right-hand side pane and select «New» > «String Value.«
6. Enter the name of the variable and press Enter.
7. Double-click on the newly created variable and enter the desired value data.
Pros | Cons |
---|---|
1. Provides direct access to the Windows Registry for system variable modifications. | 1. Advanced method that may lead to system instability if not performed correctly. |
2. Offers extensive control over system variable settings. | 2. Requires detailed knowledge of the Windows Registry and associated risks. |
3. Can be used for advanced troubleshooting and customization. | 3. Not recommended for novice users or those unfamiliar with the Windows Registry. |
Why Can’t I Edit System Variables?
There are a few reasons why you may encounter difficulties when trying to edit system variables on Windows 11. Here are some common issues and their respective fixes:
1. Limited permissions: If you do not have administrative access to your computer, you will not be able to make changes to system variables. To resolve this, ensure that you are logged in with an account that has administrative privileges.
2. Protected variables: Certain system variables are protected and cannot be modified for security or stability reasons. If you are trying to edit a protected variable, you may need to follow alternative methods or seek assistance from an IT professional.
3. Incorrect variable name: Ensure that you are using the correct variable name when attempting to modify or add a system variable. Some variables may have specific naming conventions or restrictions that need to be followed.
Implications and Recommendations
Implications and Recommendations
1. Backup your system: Before making any changes to system variables, it is important to create a backup of your system. This will allow you to revert back to the previous state if any issues arise.
2. Research variable settings: Before modifying or adding system variables, it is recommended to research their purpose and potential implications. Incorrect changes can affect the functioning of your system or specific applications.
3. Consult with IT professionals: If you are unsure about editing system variables or encounter any issues, it is advisable to seek assistance from IT professionals who have expertise in Windows systems.
5 FAQs about Editing System Variables
Q1: Can editing system variables improve system performance?
A: Editing system variables can potentially improve system performance by optimizing resource allocation, modifying system paths, or enabling specific features. However, it is important to research and understand the variables you intend to modify to avoid any negative consequences.
Q2: Are there any risks associated with editing system variables?
A: Yes, there are risks associated with editing system variables. Incorrect changes can lead to system instability, application errors, or issues with specific functionalities. It is crucial to proceed with caution, research thoroughly, and have a backup of your system before making any modifications.
Q3: Can I revert back to the default system variables?
A: Yes, you can revert back to the default system variables by either deleting the modified variables or restoring your system from a backup. However, it is recommended to create a backup before making any changes to ensure you have a reliable restore point.
Q4: What are some common system variables that users modify?
A: Some common system variables that users modify include PATH, TEMP, and JAVA_HOME. These variables allow users to add custom paths, specify temporary storage locations, and define the Java development environment, respectively.
Q5: Can I modify system variables for specific user accounts?
A: Yes, you can modify system variables specifically for individual user accounts. When using the Control Panel or the Windows 11 Settings method, select the «User variables» section instead of the «System variables» section to modify variables for a specific user.
Final Words
Editing system variables on Windows 11 can provide users with greater control over their system environment, enabling customization and optimization. By following the methods mentioned in this blog post, users can modify or add system variables according to their needs. However, it is essential to proceed with caution, research thoroughly, and create backups to ensure a smooth and secure editing process. Remember to consult with professionals if unsure or facing any difficulties.
Всем привет! Переменные среды (Environment Variables) в Windows 10 и Windows 11 – это специальные переменные, которые можно свободно использовать в командной строке, скриптах или в некоторых командах во встроенных приложениях (как например, в окне «Выполнить»). Очень полезная вещь для тех людей, которые постоянно пользуются консолью или скриптами. Например, вам необязательно постоянно вручную указывать полный путь к папке, которая находится глубоко на диске – достаточно просто прописать переменную.
Сегодня в статье я расскажу, где находятся системные переменные среды (Environment Variables) Windows, как с ними работать и создавать. Если возникнут какие-то дополнительные вопросы – пишите в комментариях.
Содержание
- Где хранятся существующие переменные
- PATH и PATHEXT
- Создание переменной
- Задать вопрос автору статьи
Где хранятся существующие переменные
Для начала давайте посмотрим, где хранятся переменные окружения в Windows 10 или 11. Уже потом познакомимся с ними поближе и на примере поймем, как они работают в системе.
- Кликните правой кнопкой по вашему компьютеру и зайдите в «Свойства».
- Если у вас обычная Home-версия – слева выбираем ссылку «Дополнительные параметры системы». Если у вас последняя Pro-версия, тогда в разделе «О программе» в правом блоке листаем в самый низ и находим ссылку с таким же названием.
- Перейдите во вкладку «Дополнительно» и нажмите по кнопке «Переменные среды…».
Далее вы увидите две таблички. В первом столбце указаны «Переменные», которые вы можете использовать. А во втором столбце – это их значения, которые уже используются программами или скриптами. Верхний блок – это переменные локального пользователя, под которым вы сидите. Они могут быть созданы установленными программами или вами. Внизу строгие системные переменные.
Также можно посмотреть весь перечень в консоли – открываем командную строку. Далее вводим команду:
set > %homepath%\desktop\set.txt
Команда выполняется очень быстро. После этого смотрим на рабочий стол и открываем текстовый файл
set.txt
В нем хранятся все уже существующие переменные, которые вы можете использовать. Все эти переменные мы используем в любом месте, в скриптах или командной строке. Например, в прошлой команде мы уже использовали переменную %homepath% – которая заменяет данные о положении папки:
C:\Users\Имя
И еще один важный момент – все переменные обрамляются знаком процента (%) с двух сторон. Размер написанных букв переменных не важен:
%homepath% = %HOMEPATH% = %Homepath%
PATH и PATHEXT
Вы могли заметить две интересные переменные PATH и PATHEXT, которые содержат в себе сразу целый массив значений. Как же с ними работать? – давайте разберем на конкретном примере.
Представим себе, что мы запускаем какую-то программу:
program.exe
С допиской переменной PATH. Если посмотреть в значения PATH, можно заметить, что это пути к определенным папкам на любом диске системы. Если вы будете использовать переменную PATH, в скрипте или консольной команде, то система пройдет по всему массиву – то есть по всем выделенным папкам и попробует найти program.exe и запустит его, если найдет. Давайте добавим свою директорию:
- Выделите PATH, нажав ЛКМ.
- Кликаем по кнопке «Изменить».
- Жмем «Создать».
- Далее вводим новую директорию. Желательно, чтобы эта директория была верной, и папка такая существовала. В конце жмем «ОК».
И еще один важный момент – после того как вы добавили новые переменные, надо чтобы они появились в системе. Для этого – или перезагружаем компьютер, или «Проводник». Только после этого переменными можно будет пользоваться. Для перезагрузки проводника, откройте консоль и введите две команды:
taskkill /F /IM explorer.exe
После этого вводим:
explorer.exe
Если вы будете работать с переменными среды в командной строке Windows 10 или Windows 11, то вам нужно также её перезапустить – закрываем и снова открываем приложение.
Ах, да…мы чуть не забыли про переменную PATHEXT, в которой хранятся различные расширения. Работает переменная примерно также. Вы можете не указывать расширение программы или объекта для запуска в скрипте или командной строке. Система автоматически будет брать расширения из массива PATHEXT и перебирать все варианты. Поэтому вместо:
program.exe
Можно просто указать:
program
Создание переменной
Давайте посмотрим, как создать переменную среды в Windows. Делается все очень просто. Выбираем верхний или нижний блок и жмем по кнопке «Создать». Еще раз повторюсь, что верхний блок предназначен для запуска команд под данным локальным пользователем.
Вводим «Имя переменной» и значение – куда можно указать путь к папке, файлу или запускаемой программе. Напомню, что здесь вы также можете использовать системные переменные, которые находятся в нижнем блоке. Жмем «ОК».
Напомню – чтобы переменная заработала, нужно будет перезагрузить «Проводник» (Explorer.exe). Про то как это сделать я уже писал в прошлой главе. Если остались вопросы и вы хотите получить помощь от портала WiFiGiD.RU – опишите свою проблему в комментариях. Также вы можете писать дополнения и предложения там же.