Настройка переменных среды 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
Все способы:
- Переменные среды 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Полезные советы и помощь
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
The Command Prompt tool is the last remnant of DOS (a former command-based operating system) preserved in Windows. You can open software and run handy tools, such as the System File Checker, with it.
For example, you can run SFC by entering sfc /scannow without specifying any path. To open third-party software in Windows 10, you usually need to input an entire directory in the Command Prompt.
What is the path environment variable in Windows?
The Edit environment variable window enables you to add new paths to third-party software to open the programs without entering their complete directories in the Command Prompt.
The path environment variable tells your system where to find the SFC, but not the software. Moreover, this variable could be a handy setting for those who often use the Command Prompt.
Microsoft even replaced the Edit System Variable dialog in earlier Windows platforms with a new Edit environment variable path window in Windows 10.
Users can edit this system path variable, and we will show you how to do this in the guide below.
-
1. Press the Windows key on your keyboard or the Start button on your taskbar to open the search box.
-
2. In the Windows search box, type advanced system settings and click on the result.
-
3. When the System properties window opens, select View advanced system settings.
-
4. Press the Environment Variables button to open the window shown below.
-
5. You need to select the Path in the System variables box. Selecting the Path and pressing the Edit button opens the window shown directly below.
-
6. The Edit environment variable window above includes the following path:
C:\Windows\system32
This is where the System File Checker tool is. To add your own path, press the New button.
-
7. Enter C: in the empty space and press the Browse button to select a folder (If you don’t enter something in the space for the new path, your selected folder directory replaces the path listed above it).
-
8. Select a folder that includes third-party software in the Browse for Folder window. For example, we selected a folder that includes Firefox.
-
9. Press the OK button on the Browse for Folder window to confirm the selection (The Edit environment variable window will include your selected path as in the snapshot below).
-
10. Click the OK button on the Edit environment variable window to close it.
-
11. Press the OK buttons on the Environment Variables and System Properties windows to close them.
-
12. Re-open the Windows search box and type cmd in it, then right-click on the result and select Run as Administrator, to open the app as below.
-
13. Now you can open the software path you added to the Edit environment variable window by entering its executable.
For example, if you added Firefox’s path to it you can open that browser by entering Firefox in the Command Prompt.
How can I edit the path on Windows 10?
The easiest way to edit the path variable in Windows 10 is through the View advanced system setting. There you can add, edit, or delete a path variable.
After that, you can set the path that’s of interest to you and modify it in any way you want.
- How to save text from the Command Prompt in Windows 10
- How to Fix Opera Browser if It Fails to Install or Download
- 10 Ways to Fix File Explorer Problems in Windows 10/11
- 16 Ways To Stop Firefox From Using Too Much Memory in 2022
- Windows Explorer stops when copying files? Fix it like a pro
A program’s executable doesn’t always match the exact software title. For example, we found that Opera’s executable was Launcher. As such, check the software’s executable title in File Explorer and then enter that in the Command Prompt.
You no longer need to enter C:\folder\sub-folder\sub-folder software title to open a program. This certainly comes in handy if you’re unsure of the software’s path.
This is a fairly simple process, and after following the steps above, setting, editing, or changing the path environment variable in Windows 10 should be more or less a formality.
If you have any other questions about the process, please leave them in the comments section below.
Matthew Adams
Windows Hardware Expert
Matthew is a freelancer who has produced a variety of articles on various topics related to technology. His main focus is the Windows OS and all the things surrounding it.
He is passionate about the tech world, always staying up-to-date with the latest and greatest. With an analytical view, he likes problem-solving, focusing on errors and their causes.
In his free time, he likes to read and write about history and tries to always develop new skills.
Sign in to your How-To Geek account
Quick Links
-
How Environment Variables Work
-
How to Edit Environment Variables
Summary
- Editing environment variables can save time in Command Prompt, make scripts more concise, and customize where Windows stores files.
- Environment variables point to important directories or relay information about your PC, and can be read by any program or script.
- The Path variable defines which folders are checked for executables, and adding folders to it allows for easier execution of commands and scripts in Command Prompt.
Editing your PC’s environment variables can save you time in Command Prompt and make your scripts more concise. It also lets you customize where Windows stores certain files. Find out how to edit them here.
How Environment Variables Work
Environment variables can be used to point to or set important directories, like the location of the Windows Temp folder, or they can they relay important information about your PC, like the version of Windows it is running or the number of processor cores it has available. Environment variables be read by any program or script that runs on your computer. Environment variables can be defined for individual user accounts, or on a system-wide basis.
One environment variable of note is the Path variable. Path defines what folders are checked for executables when a command is run in a terminal or a script. Take Notepad as an example— you can type notepad
into Command Prompt and it will launch immediately. If you type chrome
, however, you’ll get an error message. The error occurs because the Notepad executable is in a folder defined in the Path, but the Chrome executable is not.
By default, Path only points to a few Windows folders, but you can easily add more.
Changing environment variables can result in your PC malfunctioning. If you’re going to add, edit, or delete an environment variable, be sure to double-check what it is you’re doing.
How to Edit Environment Variables
There are some minor differences between the user interfaces of Windows 10 and Windows 11, but the basic process of editing environment variables is the same.
To configure your environment variables, click the Start button, then type «environment properties» into the search bar and hit Enter. In the System Properties window, click «Environment Variables.»
Click on the variable you’d like to change, click «Edit.»
Many environment variables will simply take a name and value, like «Number of processors.» All you have to do to edit them is to change the value, and click «OK.»
Adding an environment variable works the exact same way, except you must specify the variable name and value. The variable value can take multiple values if you want, but the values must be separated by semicolons. Once you’ve named your variable and assigned a value, click «OK.»
Some environment variables, like Path, look a little different, though they function in exactly the same way. The Path variable is given as a list from which you can add, edit, or delete entries.
You can add another folder to the Path by clicking «New,» and then specifying the folder.
If you write a lot of batch or PowerShell scripts, or frequently use non-Windows command-line applications, it is probably worth the effort to customize your environment variables — you’ll save a ton of time in the long run.
Why PATH Variables Matter So Much
Ever wondered why some programs run perfectly fine without specifying their full location, while others need a complete path to execute? The magic behind this is something called the PATH environment variable. This might sound like tech jargon, but it’s actually pretty straightforward. Basically, the PATH variable is a list of directories that Windows searches when you try to run a command or program. If the executable is in one of these directories, you can run it without typing the full path. So, let’s dive into what this really means and why it’s so important.
Imagine trying to find a book in a huge library without any organization. It’d be a nightmare, right? The PATH variable is like the library’s organizational system. It tells Windows exactly where to look for the programs you want to run, making everything faster and more efficient.
Think about it: you’ve got a bunch of apps and programs installed on your computer, and each one might have its own set of executable files. The PATH variable lets Windows know where to find these files quickly. It’s like having a map that points directly to where each program is stored. Pretty handy, huh?
And here’s the kicker: the PATH variable isn’t just for system-wide settings. You can customize it for individual users too. This means you can set up different environments for different users on the same computer. For example, a developer might need access to specific tools that a regular user doesn’t.
So, why does this matter? Well, it makes your computer run more smoothly and helps you avoid those annoying errors when a program can’t find the files it needs. Plus, it’s a great way to keep your system organized and efficient.
The way I see it (but I could be wrong), understanding PATH variables can make a big difference in how well your computer performs. And the good news is, you don’t need to be a tech genius to figure it out. With a bit of know-how, you can set up your PATH variable like a pro.
Before we move on, here’s a quick fun fact: did you know that the PATH variable has been around since the early days of computing? It’s one of those fundamental concepts that has stood the test of time. Anyway, let’s get into the details of how to actually set and edit these variables.
Setting Up PATH Variables in Windows
So, you want to set up or edit your PATH variable in Windows? Great! Let’s walk through the steps. It’s actually pretty simple once you know what you’re doing.
The easiest way to edit your PATH variable is through the Windows Settings menu. Here’s how you do it:
- Open the Search menu on the Taskbar and type ‘Settings’. Click on it to open.
- In the Settings panel, click on ‘System’ from the left menu.
- Go to ‘About’ and then click on ‘Advanced System Settings’. This opens the System Properties dialog box.
- In the System Properties window, click on the ‘Advanced’ tab and then click on the ‘Environment Variables’ button at the bottom-right.
- This opens the Environment Variables panel. You’ll see two sections: System variables and User variables. Choose the one that fits your needs and select ‘PATH’ from the list.
- Click on the ‘Edit’ button to modify the existing paths.
You can now add, edit, or delete paths as needed. Just remember to be careful, because messing up the PATH variable can cause some serious issues with your system. If you’re unsure about a path, you can use the ‘Browse’ option to search for it.
And that’s it! Once you’re done, click ‘OK’ to save your changes. Your new PATH variable is now set up.
Editing PATH Variables without Admin Rights
What if you don’t have admin rights on your computer? No problem. You can still edit the PATH variable for your user account through the Control Panel. Here’s how:
- Open the Control Panel and select to view as ‘Small icons’.
- Click on ‘User Accounts’.
- On the left, click on ‘Change my environment variables’.
- This opens the Environment Variables dialog box, but you’ll only be able to edit User variables, not System variables.
This method is great for making changes that only affect your user account. It’s a bit more limited, but it gets the job done.
Using Command Prompt
If you’re more comfortable with the command line, you can also edit the PATH variable using the Command Prompt. Here’s how:
- Search for ‘CMD’ on the Taskbar and run it as an administrator.
- Enter the command ‘setx PATH «%PATH%;C:\Your\New\Path»‘. This appends the new path to your existing PATH variable.
- To remove a path, you can use the ‘setx’ command with the ‘/M’ flag to modify the system PATH variable.
Using the Command Prompt can be a bit trickier, but it’s a powerful tool once you get the hang of it. Just make sure to double-check your commands before hitting enter.
Common PATH Variable Issues and How to Fix Them
Even with the best intentions, things can go wrong when editing the PATH variable. Here are some common issues and how to fix them:
PATH Too Long
One of the most common problems is the PATH variable becoming too long. Windows has a limit on the length of the PATH variable, and if you exceed it, you’ll run into issues. The fix? Clean up your PATH variable by removing any unnecessary or duplicate entries. You can also shorten the paths by using shorter directory names.
Incorrect Paths
Another common issue is having incorrect paths in your PATH variable. This can happen if you mistype a path or if a directory has been moved or deleted. The solution is to carefully check each path and make sure it’s correct. You can use the ‘Browse’ option in the Environment Variables dialog box to find the correct path.
Conflicting Paths
Sometimes, you might have conflicting paths in your PATH variable. This can cause programs to behave unexpectedly or not run at all. The best way to avoid this is to keep your PATH variable organized and only include the paths you actually need. If you suspect a conflict, try temporarily removing paths one by one to see if the issue resolves.
Advanced Tips for Managing PATH Variables
Once you’ve got the basics down, there are a few advanced tips that can help you manage your PATH variable like a pro.
Using Batch Scripts
If you find yourself frequently editing the PATH variable, you might want to consider using batch scripts. A batch script is a simple text file with a .bat extension that contains a series of commands. You can use a batch script to automate the process of adding or removing paths from your PATH variable. Here’s an example of a batch script that adds a new path:
@echo off
setx PATH "%PATH%;C:\Your\New\Path"
echo PATH variable updated.
To use this script, just save it as a .bat file and run it. The script will automatically update your PATH variable with the new path.
Environment Variable Editor Tools
There are also third-party tools available that can make managing your PATH variable even easier. Tools like Rapid Environment Editor and Path Editor offer user-friendly interfaces and advanced features for editing environment variables. These tools can be especially helpful if you need to manage PATH variables on multiple computers or for multiple users.
Backing Up Your PATH Variable
Before making any changes to your PATH variable, it’s a good idea to back it up. This way, if something goes wrong, you can easily restore your original settings. To back up your PATH variable, simply copy the current value to a text file and save it somewhere safe. If you need to restore it, you can just copy the value back into the PATH variable.
What’s Next?
So, there you have it, a comprehensive guide to setting up and managing PATH environment variables in Windows. You might be wondering, what’s next? Well, once you’ve mastered PATH variables, you can start exploring other environment variables and see how they can help you customize your system even further. There’s always more to learn when it comes to computers, and every new skill you pick up makes you that much more efficient and effective.
And remember, if you ever run into trouble, don’t hesitate to ask for help. There are plenty of resources available online, and chances are, someone else has run into the same issue before. The tech community is full of helpful people who are more than willing to share their knowledge and expertise.
So go ahead, dive in, and start experimenting with your PATH variable. You might be surprised at how much of a difference it can make in your daily computing life. And who knows? You might even discover a new passion for tinkering with your system settings. The possibilities are endless, and the journey is always rewarding.
FAQ
- What happens if I mess up my PATH variable?
- If you mess up your PATH variable, some programs might not run correctly, or you might see errors when trying to execute commands. The best thing to do is restore your PATH variable from a backup or carefully edit it to fix any issues.
- Can I have multiple paths in my PATH variable?
- Yes, you can have multiple paths in your PATH variable. They should be separated by semicolons (;). Just make sure not to exceed the length limit.
- How do I know if my PATH variable is too long?
- If your PATH variable is too long, you might see an error message when trying to save it, or some programs might not run correctly. To fix this, remove any unnecessary or duplicate entries.
- What is the difference between System and User variables?
- System variables apply to all users on the computer, while User variables apply only to the specific user account. System variables are useful for settings that need to be consistent across all users, while User variables are good for customizing individual user environments.
- Can I use the Command Prompt to edit System variables?
- Yes, you can use the Command Prompt to edit System variables, but you need to run it as an administrator and use the ‘/M’ flag with the ‘setx’ command to modify the system PATH variable.
- Is it safe to edit the PATH variable?
- Editing the PATH variable is generally safe as long as you know what you’re doing. Always back up your current PATH variable before making changes, and be careful to avoid typos or incorrect paths. If you’re unsure, it’s a good idea to consult a more experienced user or look up guides online.