Как добавить папку в path windows

Для быстрого доступа к командам в командной строке без необходимости ввода полного пути к исполняемому файлу можно добавить путь к папке с этими исполняемыми файлами в переменную PATH в Windows, особенно это может быть полезным при работе с adb, pip и python, git, java и другими средствами разработки с отладки.

В этой пошаговой инструкции о том, как добавить нужный путь в системную переменную PATH в Windows 11, Windows 10 или другой версии системы: во всех актуальных версиях ОС действия будут одинаковыми, а сделать это можно как в графическом интерфейсе, так и в командной строке или PowerShell. Отдельная инструкция про переменные среды в целом: Переменные среды Windows 11 и Windows 10.

Добавление пути в PATH в Свойствах системы

Для возможности запуска команд простым обращением к исполняемому файлу без указания пути, чтобы это не вызывало ошибок вида «Не является внутренней или внешней командой, исполняемой программой или пакетным файлом», необходимо добавить путь к этому файлу в переменную среды PATH.

Шаги будут следующими:

  1. Нажмите клавиши Win+R на клавиатуре (в Windows 11 и Windows 10 можно нажать правой кнопкой мыши по кнопке Пуск и выбрать пункт «Выполнить»), введите sysdm.cpl в окно «Выполнить» и нажмите Enter.
  2. Перейдите на вкладку «Дополнительно» и нажмите кнопку «Переменные среды».
    Открыть настройки переменных среды Windows

  3. Вы увидите список переменных среды пользователя (вверху) и системных переменных (внизу). PATH присутствует в обоих расположениях.
    Переменная среды PATH пользователя и системная

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

  6. После ввода всех необходимых путей нажмите «Ок» — ваша папка или папки добавлены в переменную PATH.

Внимание: после добавления пути в переменную PATH потребуется перезапустить командную строку (если она была запущена в момент изменения), чтобы использовать команды без указания полного пути.

Как добавить путь в переменную PATH в командной строке и PowerShell

Вы можете добавить переменную PATH для текущей сессии в консоли: то есть она будет работать до следующего запуска командной строки. Для этого используйте команду:

set PATH=%PATH%;C:\ваш\путь

Есть возможность добавить путь в PATH с помощью командной строки и на постоянной основе (внимание: есть отзывы, что может повредить записи в переменной PATH, а сами изменения производятся для системной переменной PATH), команда будет следующей:

setx /M path "%path%;C:\ваш\путь"
Добавление в PATH в командной строке

Набор команд для добавления пути в переменную PATH пользователя с помощью PowerShell:

$PATH = [Environment]::GetEnvironmentVariable("PATH")
$my_path = "C:\ваш\путь"
[Environment]::SetEnvironmentVariable("PATH", "$PATH;$my_path", "User")

Если требуется добавить путь в системную переменную PATH для всех пользователей, последнюю команду изменяем на:

[Environment]::SetEnvironmentVariable("PATH", "$PATH;$my_path", "Machine")

The Path environment variable feature in Windows is very important because it lets your computer know where to find the programs when you run them through Command Prompt. For example, if you add a folder path to the “Path” environment variable, you can run any program in that path by entering only its name (e.g. “name.exe”) instead of its whole address every time you want to run it.

This guide will show you how to add a folder to the Path environment variable in Windows 11 or 10. Doing this for a program you often run will save you a lot of hassle and time when executing commands that involve the program.

Add Folder to Path Environment Variable in Windows 11 10

What is the “Path” environment variable?

The Path environment variable is like a list inside your Windows operating system that helps your computer find and run programs directly from a command prompt or PowerShell without needing the full address of the program. It’s a bunch of folder addresses stuck together with semicolons (;). When you try to start a program, Windows looks through these folders in the order they’re listed to find the program’s executable file.

The big deal about the Path variable is it will truly save you a lot of time. Instead of typing the full path every time you want to run a program, you can just tell your computer to run it by typing only its name, and if the program’s folder is in the Path, Windows will know where to find it.

Related issue: Batch (.BAT) Files Not Running in Windows 11/10

Here’s what a Path environment variable look like:

C:\Windows\system32;C:\Windows;C:\Program Files\Java\jdk1.8.0_281\bin

In this example, there are three directories listed. If you run a command, Windows will check these directories in this order to find the program you’re trying to start. If it’s not in any of these, you’ll see an error message.

“[Program] is not recognized as an internal or external command” error

If you’re trying to run a program called “custom-command,” but its folder isn’t listed in the Path. When you try to start it, you might see an error saying:

'custom-command' is not recognized as an internal or external command, operable program or batch file.

is not recognized as an internal or external command Windows 11

This error means Windows can’t find the program in any of the Path directories. To fix this, you need to add the program’s folder to the Path, which we’ll talk about next, or simply type the full path to the program.

Useful tip: How to List Installed Programs in Windows 11

How to add a folder to the “Path” environment variable in Windows 11 or 10

Adding a folder to the Path can be done through a few methods – the system properties, CMD or PowerShell. Choose a method that you’re comfortable with.

Using System Properties

This method should be the easiest and most friendly for people who are not very into commands because it uses the graphical interface of the System Properties window to add or change the Path.

  1. Hit Windows + X and choose “System” from the menu that pops up.
  2. In the System window, click on “Advanced system settings” on the right.
    Windows 11 advanced system settings

  3. Go to the “Advanced” tab in the System Properties dialog and hit the “Environment Variables” button.
    View Environment Variables Windows 11

  4. Find the “Path” variable under “System variables,” select it, and press “Edit.” This opens the “Edit environment variable” window.
    Add Directory to Path Environment Variable Windows 11 10

  5. Here, you’ll see all the folders already in the Path. To add a new one, click “New” and type or paste its address. Tip: Use the “Copy as Path” option to get the folder path right, starting from the root (like C:\Users\YourUsername\custom-folder).
    Add Folder to Path Environment Variable in Windows 11 10

  6. Hit “OK” when you’re done. Your new folder is now part of the Path, and Windows will check it when looking for programs to run.

See also: Change File(s) Date & Timestamp via CMD or PowerShell

Using Command Prompt

In this method, you will use the Command Prompt to change the Path environment variable.

  1. Start a Command Prompt with admin rights by right-clicking on the Start button, choosing “Windows Terminal (Admin)”, and then picking “Command Prompt” from the list.
    Open Command Prompt from Windows Terminal

  2. Type this command, but use your own folder path instead of “YourFolderPath”:
    setx PATH "%PATH%;YourFolderPath"

    This adds your new folder path to the current Path variable. It’s important to keep the “%PATH%;” part to not lose the paths already there.
    To add the folder path in the system environment and prevents the system Path from being duplicated in the user Path, add the /M option like this:

    setx /M PATH "%PATH%;YourFolderPath"

    Add Folder to Path Environment Variable CMD

  3. Close the Command Prompt and open it again to see your changes. Your new folder should now be part of the Path environment variable.

Using PowerShell

This method involves PowerShell to update the Path environment variable.

  1. Open PowerShell with admin rights by right-clicking on the Start button and choosing “Windows Terminal (Admin)”.
  2. Type this command, swapping “YourFolderPath” with your folder path:
    [Environment]::SetEnvironmentVariable("Path",
    [Environment]::GetEnvironmentVariable("Path",
    [EnvironmentVariableTarget]::Machine) + ";YourFolderPath",
    [EnvironmentVariableTarget]::Machine)
    

    Add Folder to Path Environment Variable PowerShell

    This gets the current Path variable, adds your new folder path, and then updates the Path variable. The “;YourFolderPath” adds your new folder after the existing paths.

  3. Close PowerShell and open it again to check the changes. Your new folder should now be in the Path environment variable.

Note: If you need to write a multi-line command in PowerShell, press Shift + Enter to go to a new line without running the command. Press Enter to run it after you’ve typed all of it. This can be helpful for long commands or scripts.

Checking the changes

To make sure the folder is now in the Path environment variable, open a new Command Prompt window and type:

echo %PATH%

Look at the output and check if the folder path you added is there.

Check Path Environment Variable Windows 11 10

Some common issues

The below are some common problems you might encounter when adding a folder to the Path environment variable in Windows.

  • If CMD still gives you error after adding the path of a program you want to run, double-check for typos or mistakes in the folder path. It should be a full path without special characters.
  • Changes to the Path variable only affect new Command Prompt or PowerShell sessions. Restart them to see the changes.
  • If there’s still a problem, there might be a conflict with other software. Look through the Path variable for any outdated or duplicate paths and remove them.

Other common mistakes

It’s easy to make a small mistake that can cause big problems when you’re updating the Path variable.

  • Always back up the current state of the Path variable before making changes. This way, if something goes wrong, you can simply restore it to its original state.
  • Never delete the existing entries in the Path variable unless you are certain they are no longer needed. Removing important paths can stop other programs from running properly.

One last thing: Knowing Path variable priorities

The order of paths in the Path variable matters a lot because Windows checks them in sequence to find the executable files.

If two folders in the Path contain an executable with the same name, Windows will run the one in the folder that appears first in the Path order. You might want to place frequently accessed program directories higher up in the Path to speed up their launch times.

Способ 1: Переменные среды

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

  1. Нажатием клавиш Win + R вызовите диалоговое окошко быстрого запуска и выполните в нем команду systempropertiesadvanced, чтобы открыть дополнительные свойства системы.
  2. Как добавить путь в path в Windows 10-1

  3. Нажмите кнопку «Переменные среды», чтобы открыть одноименную оснастку.
  4. Как добавить путь в path в Windows 10-2

  5. В Windows доступны две переменные Path: пользователя и системы. Если вносимые изменения должны затронуть всех пользователей, необходимо выбрать системную переменную. Выделите последнюю мышкой и нажмите кнопку «Изменить».
  6. Как добавить путь в path в Windows 10-3

  7. Откроется окошко со списком уже существующих путей. Нажмите в нем кнопку «Изменить текст».
  8. Как добавить путь в path в Windows 10-4

  9. Нажмите «OK» в окошке с предупреждением.
  10. Как добавить путь в path в Windows 10-5

  11. Откроется окно редактирования переменной. Скопируйте свой путь и вставьте его в конец уже имеющегося значения в поле «Значение переменной», отделив его точкой с запятой. Перед точкой с запятой также следует добавить слеш, если таковой отсутствует.
  12. Как добавить путь в path в Windows 10-6

  13. Сохраните настройки и перезагрузите компьютер.

После этого обращаться к файлам и каталогам по добавленному пути можно будет напрямую, используя их имена.

Способ 2: Редактирование реестра

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

  1. Откройте «Редактор реестра» командой regedit в окошке Win + R.
  2. Как добавить путь в path в Windows 10-7

  3. Перейдите к ветке HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment, если нужно отредактировать системную переменную, или HKCU\Environment, если целью является пользовательская переменная. В правой колонке отыщите строковый параметр с названием «Path» и кликните по нему дважды, чтобы открыть окошко редактирования значения.
  4. Как добавить путь в path в Windows 10-8

  5. Добавьте в конец текущего значения свой путь, отделив его точкой с запятой. Как и в предыдущем способе, перед разделителем необходимо добавить слеш.
  6. Как добавить путь в path в Windows 10-9

  7. Сохраните настройки, закройте «Редактор реестра» и перезагрузите компьютер.

Способ 3: Сторонние программы

Для работы с переменными Windows существуют также специальные программы-редакторы. Примером такой программы является Rapid Environment Editor. Приложение поддерживает просмотр переменных окружения, выбор значений переменных из дерева каталогов, проверку корректности перечисленных в переменных путей и имен файлов, экспорт переменных и их значений в reg-файл.

Скачать Rapid Environment Editor с официального сайта

  1. Скачайте архив с программой с сайта разработчика, распакуйте и запустите исполняемый файл rapidee.exe от имени администратора. Выберите на панели инструментов, если нужно, русский язык интерфейса.
  2. Приложение имеет двухпанельный интерфейс: на левой панели расположен список системных переменных, в правой колонке перечислены пользовательские переменные окружения. Скопируйте в буфер обмена добавляемый путь, нажмите правой кнопкой мыши по переменной Path и выберите в контекстном меню опцию «Добавить значение».
  3. Как добавить путь в path в Windows 10-10

  4. Вставьте путь в появившуюся форму и нажмите клавишу ввода.
  5. Как добавить путь в path в Windows 10-11

  6. Сохраните результат редактирования, выбрав в главном меню «Файл» опцию «Сохранить».
  7. Как добавить путь в path в Windows 10-012

При необходимости новый элемент (путь) может быть вставлен в начало, середину или конец текущего значения переменной. Перемещать его в Rapid Environment Editor можно простым перетаскиванием.

Существуют также и другие способы добавления путей в переменную Path, но они гораздо менее удобны. Например, переменная пути может быть отредактирована в «Командной строке» или консоли «PowerShell».

Наша группа в TelegramПолезные советы и помощь

Работа с фронтендом сейчас немыслима без использования консоли (командной строки): набираем какую-либо команду с аргументами — получаем результат. Ну и для некоторых операций консоль дает выигрыш по скорости в сравнении с GUI (сравните создание файловой структуры из GUI с командой mkdir -p project/{js,fonts,scss}).

Зачем это всё

Хочется набирать в консоли subl . для открытия текущей директории как папки проекта или subl filename.html для открытия файла в ST3. При этом не хочется блокировать возможность работы с консолью, как в случае с алиасом.

PATH — это системная переменная, содержащая список директорий, в которых ОС будет искать исполняемый файл при вызове команды из консоли.

В Windows 10 можно добраться до настройки PATH так: Этот компьютер → Свойства → Дополнительные параметры системы → Дополнительно → Переменные среды. Или вызовом «Изменение переменных среды текущего пользователя» в результатах поиска.

В окошке «Переменные среды» в блоке «Переменные среды пользователя %USERNAME%» находим строку PATH, выделяем кликом, жмем кнопку «Изменить…» и в появившемся окошке нажимаем «СОздать» для добавления ещё одного элемента. В самом элементе нужно вписать путь к папке Sublime Text (путь к файлу subl.exe, который должен лежать в папке программы). В моем случае получилось так:

c:\Program Files\Sublime Text 3\

После перезапуска консоли можно наслаждаться командой subl.

Introduction 

Recently, I needed to add a directory to the PATH system variable of Windows 10. The PATH is a system variable that allows Windows to locate executables from the command line or the Terminal window.

In this article, I will show you how to add a folder to the Windows 10 PATH variable.

Step 1. Press WIN+S to launch Windows Search on your Windows 10 machine. You will see Search Textbox.

 

Step 2. Type “environ..” in the Windows Search Textbox. You will see “Edit the system environment variables” as a result of the Best match list. Select this option.

 

Step 3. This will launch the System Properties window. On this window, we can review Computer Name, Hardware, and other Advanced properties.

 

On the Advanced tab, we can set Performance, User Profiles, and Startup and Recovery options. The last button is the Environment Variables. Click on this button.

Step 4. It will launch the Environment Variables window where you can see all variables and their values. As you can see from the following window, there are User variables and System variables.

In System variables, one of the variables is Path. See in the above image.

Step 5. Double click on the Path variable.

You will see a list of all Path variables where you can edit them, add a new Path variable, and delete an existing variable.

 

Step 6. Click on New button. It will enter a new editable row where you can type a new path.

 

Step 7. Click OK. Your PATH variable is now added.

Watch this video for more details: 

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Windows 7 разделитель на панели задач
  • Kyocera ecosys m2235dn драйвер windows 7
  • Чем удалить неудаляемые файлы в windows 10
  • Age of empires 2 definitive edition на windows 7
  • Как отключить рекламу в приложениях windows