How to add path to path windows

How to add path to path windows

Adding and Editing PATH Environment Variables in Windows

For example, the Notepad.exe application resides in the C:\Windows\system32 directory. However, if we wish to open the Notepad application via the Windows Command Line, we need only type:

Opening Notepad.exe From the Windows Command Line:

This works because the Path variable on Windows by default contains a list of directories where application files and scripts are likely to be located. Each directory in the list is separated by a semi-colon.

Similarly, there is another environment variable, PATHEXT which specifies a list of file extensions which might be found when searching for the proper file within the paths in the Path variable. This is why we are able to type simply “Notepad” at the command prompt, instead of Notepad.exe.

Windows will first search the current directory (where the command prompt is a the time the command is executed) to find a name matching the one typed into the terminal, and then search the directories in the Path variable in order, beginning with the most likely locations, and continue until either a matching file name is located, or else return the “… is not recognized blah blah” message at the terminal.

Once a file with a matching name is located, Windows attempts to match the file extension (if one is present), again in the order specified in the PATHEXT variable. If a match is found, the file is processed accordingly.

There are both User-specific and machine-level PATH variables. Machine Path variables are available globally across the machine, and can only be modified by administrators. User Environment variables can be modified by both administrators, and the user with which the current profile is associated.

Adding a Directory to the User Path Variable from the Command Line

Any user can modify their own PATH variable from the Command Line (unless they have been specifically denied this ability by an administrator).

For example, when we wish to use SQLite from the Windows Command Line, we download the SQLite binaries, and place them in the directory of choice. However, in order to use the SQLite Command Line application without either navigating directly to the folder in which we placed it, or entering the full file path into our Windows Command Line, we need to add the directory containing the SQLite.exe to our User or System PATH environment variable.

Let’s say a user has downloaded the sqlite3.dll and sqlite3.exe binaries and located them in the directory C:\SQLite.

Now, in order to invoke the sqlite3.exe from the command line, we need to add the C:\SQLite directory to our PATH environment variable. We can do this from the command line by using the setx command:

The setx Command – Syntax:

We can examine the contents of the PATH variable by typing:

Output PATH Variable to the Console:

Which gives the output:

Results of Echo %PATH% Command:

We can see here that C:\SQLite has now been added to the paths available to the current user.

Adding a Directory to the System Path Variable from the Command Line

In the previous section, we used the setx command to add a directory to the current user’s Path variable. Sometimes, we want to make variables available at the system, or machine level. In that case, we use the same setx command in conjunction with the /m flag. However, we need to run the Command Terminal as Administrator for this to work:

Add a Directory the the System PATH Variable Using the /m Flag:

Adding a Directory to the Path Variable from the GUI

Or, we can do this using the GUI by navigating to Control Panel => All Control Panel Items => System, and then selecting the “Advanced System Settings” link:

Locate Advanced System Settings in Control Panels:

How to add path to path windows. Смотреть фото How to add path to path windows. Смотреть картинку How to add path to path windows. Картинка про How to add path to path windows. Фото How to add path to path windows

Then locate the “Environment Variables” button:

Open Environment Variables:

How to add path to path windows. Смотреть фото How to add path to path windows. Смотреть картинку How to add path to path windows. Картинка про How to add path to path windows. Фото How to add path to path windows

Opening Environment Variables, we see the following:

Editing Environment Variables:

How to add path to path windows. Смотреть фото How to add path to path windows. Смотреть картинку How to add path to path windows. Картинка про How to add path to path windows. Фото How to add path to path windows

Also note, there is not currently a Path variable for me, the current user. We will need to add one, and then add our new path to it:

Adding a User Path Variable in the Windows GUI:

How to add path to path windows. Смотреть фото How to add path to path windows. Смотреть картинку How to add path to path windows. Картинка про How to add path to path windows. Фото How to add path to path windows

Once we hit OK, We see we have the single item added to our user path variable.

Added Path Variable to User Environment Variables:

How to add path to path windows. Смотреть фото How to add path to path windows. Смотреть картинку How to add path to path windows. Картинка про How to add path to path windows. Фото How to add path to path windows

For some reason, this works differently than when we do this from the Command Line, when we use the setx command from the terminal, the entirety of the system path variable is copied into the user path variable, including the new entry.

If we have Administrator permissions on our machine, we can do the same for the System PATH variable if we so choose.

Removing Directories from the PATH Variable

In some cases, we may need to remove a directory from our PATH variable. In these cases it is recommended to use the GUI, or edit the registry. It’s easiest to simply open the GUI, copy the contents of the PATH variable (either the User Path or the System Path) to a text editor, and remove the entries you want to delete. Then paste the remaining text back into the Edit Path window, and save.

Windows CMD: PATH Variable – Add To PATH – Echo PATH

PATH is an environment variable that specifies a set of directories, separated with semicolons ( ; ), where executable programs are located.

In this note i am showing how to print the contents of Windows PATH environment variable from the Windows command prompt.

I am also showing how to add a directory to Windows PATH permanently or for the current session only.

Cool Tip: List environment variables in Windows! Read More →

Echo Windows PATH Variable

Print the contents of the Windows PATH variable from cmd :

The above commands return all directories in Windows PATH environment variable on a single line separated with semicolons ( ; ) that is not very readable.

To print each entry of Windows PATH variable on a new line, execute:

Cool Tip: Set environment variables in Windows! Read More →

Add To Windows PATH

Warning! This solution may be destructive as Windows truncates PATH to 1024 characters. Make a backup of PATH before any modifications.

Save the contents of the Windows PATH environment variable to C:\path-backup.txt file:

Set Windows PATH For The Current Session

Set Windows PATH variable for the current session:

Set Windows PATH Permanently

Run as Administrator: The setx command is only available starting from Windows 7 and requires elevated command prompt.

Permanently add a directory to the user PATH variable:

Permanently add a directory to the system PATH variable (for all users):

Info: To see the changes after running setx – open a new command prompt.

How to set the path and environment variables in Windows

Setting the path and environment variables differs depending on the Windows operating system version on your computer. Select a link below for your version of Windows and follow the steps.

Administrator privileges are required to modify the path and environment variables.

Setting the path and variables in Windows 11

How to add path to path windows. Смотреть фото How to add path to path windows. Смотреть картинку How to add path to path windows. Картинка про How to add path to path windows. Фото How to add path to path windows

You can edit other environment variables by highlighting the variable in the System variables section and clicking Edit. If you need to create a new environment variable, click New, and enter the variable name and value.

To view and set the path through the Windows command line, use the path command.

Setting the path and variables in Windows 10

How to add path to path windows. Смотреть фото How to add path to path windows. Смотреть картинку How to add path to path windows. Картинка про How to add path to path windows. Фото How to add path to path windows

You can edit other environment variables by highlighting the variable in the System variables section and clicking Edit. If you need to create a new environment variable, click New, and enter the variable name and value.

To view and set the path through the Windows command line, use the path command.

Setting the path and variables in Windows 8

How to add path to path windows. Смотреть фото How to add path to path windows. Смотреть картинку How to add path to path windows. Картинка про How to add path to path windows. Фото How to add path to path windows

You can edit other environment variables by highlighting the variable in the System variables section and clicking Edit. If you need to create a new environment variable, click New, and enter the variable name and value.

To view and set the path through the Windows command line, use the path command.

Setting the path and variables in Windows Vista and Windows 7

How to add path to path windows. Смотреть фото How to add path to path windows. Смотреть картинку How to add path to path windows. Картинка про How to add path to path windows. Фото How to add path to path windows

You can edit other environment variables by highlighting the variable in the System variables section and clicking Edit. If you need to create a new environment variable, click New, and enter the variable name and value.

To view and set the path through the Windows command line, use the path command.

Setting the path and variables in Windows 2000 and Windows XP

The path is now managed by Windows 2000 and Windows XP and not the autoexec.bat or autoexec.nt files, as was done with earlier versions of Windows. To change the system environment variables, follow the steps below.

How to add path to path windows. Смотреть фото How to add path to path windows. Смотреть картинку How to add path to path windows. Картинка про How to add path to path windows. Фото How to add path to path windows

You can edit other environment variables by highlighting the variable in the System variables section and clicking Edit. If you need to create a new environment variable, click New, and enter the variable name and value.

To view and set the path through the Windows command line, use the path command.

What is the default Windows %PATH%?

The path is based on programs installed on the computer, so there is no «default path.» However, the Windows minimum path is often the path below.

Keep in mind that as you install programs, the path is updated with the paths for the newly installed programs. So, if you have erased your path after installing other programs, those programs may be affected.

Setting path in the MS-DOS and Windows command line

To view and set the path in MS-DOS and the Windows command line, use the path command.

Системная переменная PATH Windows

Введение

Для чего используется

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

Искать по всему жёсткому диску было бы слишком долго, поэтому поиск осуществляется только по некоторым директориям.

Список этих особых директорий хранится в системной переменной PATH.

Пример

Без предварительной подготовки ввод Firefox в консоль выдаст ошибку.

‘firefox’ is not recognized as an internal or external command, operable program or batch file.

Чтобы решить эту проблему нужно добавить директорию с испоняемым файлом firefox в PATH

Добавить директорию в PATH

How to add path to path windows. Смотреть фото How to add path to path windows. Смотреть картинку How to add path to path windows. Картинка про How to add path to path windows. Фото How to add path to path windows

Правый клик на Этот Компьютер (This PC) → Свойства (Properties)

How to add path to path windows. Смотреть фото How to add path to path windows. Смотреть картинку How to add path to path windows. Картинка про How to add path to path windows. Фото How to add path to path windows

Дополнительные параметры системы (Advanced system settings)

How to add path to path windows. Смотреть фото How to add path to path windows. Смотреть картинку How to add path to path windows. Картинка про How to add path to path windows. Фото How to add path to path windows

Дополнительно (Advanced) → Переменные среды (Environment Variables)

How to add path to path windows. Смотреть фото How to add path to path windows. Смотреть картинку How to add path to path windows. Картинка про How to add path to path windows. Фото How to add path to path windows

Если хотите менять для всей системы, то в окошке «Переменные среды» (System Variables) найдите строку PATH в блоке «Системные переменные» (System variables) выделите кликом и нажмите кнопку «Изменить. » (Edit. )

Если хотите менять только для своего пользователя, то делайте это в блоке «Переменные среды пользователя %USERNAME%» (User variables for %USERNAME%)

How to add path to path windows. Смотреть фото How to add path to path windows. Смотреть картинку How to add path to path windows. Картинка про How to add path to path windows. Фото How to add path to path windows

Создайте новый путь (New)

How to add path to path windows. Смотреть фото How to add path to path windows. Смотреть картинку How to add path to path windows. Картинка про How to add path to path windows. Фото How to add path to path windows

Введите адрес директории в которой лежит нужная программа. В нашем случае это

C:\Program Files (x86)\Mozilla Firefox

How to add path to path windows. Смотреть фото How to add path to path windows. Смотреть картинку How to add path to path windows. Картинка про How to add path to path windows. Фото How to add path to path windows

Перезапустите консоль или открываем новую и пишем там firefox.

Браузер должен запуститься.

Изучить содержимое PATH

В PowerShell достаточно выполнить

В cmd.exe посмотреть список переменных окружения можно выполнив команду set без параметров.

Выдача содержит системные переменные и переменные пользователя а также дополнительную информацию. Содержимое PATH выделено зелёным.

How to add path to path windows. Смотреть фото How to add path to path windows. Смотреть картинку How to add path to path windows. Картинка про How to add path to path windows. Фото How to add path to path windows

Ошибки

-bash: syntax error near unexpected token `(‘

Скорее всего Вы пытаетесь добавить в unix PATH адрес из Windows, c пробелами, скобками и так далее.

andrey@olegovich-10:/usr/share$ export PATH=/mnt/c/Program Files (x86)/Common Files/Oracle/Java/javapath_target_1128437:$PATH

-bash: syntax error near unexpected token `(‘

andrey@olegovich-10:/usr/share$ export PATH=$PATH:/mnt/c/Program\ Files\ \(x86\)/Common\ Files/Oracle/Java/javapath_target_1128437

Postgesql

В моём случае psql.exe находится в папке C:\Program Files\PostgreSQL\12\bin

Подпишитесь на Telegram канал @aofeed чтобы следить за выходом новых статей и обновлением старых

IT-блог о веб-технологиях, серверах, протоколах, базах данных, СУБД, SQL, компьютерных сетях, языках программирования и создание сайтов.

Как настроить и добавить путь к программе в системную переменную Path в Windows 10, Windows 8 и Windows 7

Привет, посетитель сайта ZametkiNaPolyah.ru! Продолжим разбираться с командами и системными утилитами в операционной системе Windows 10, на этот раз будет разговор о переменной PATH в Windows. Всё дело в том, что системная переменная PATH дает нам возможность расширить список команд командной строки Windows, как это сделать, вы узнаете из этой публикации. Здесь мы с вами поговорим о назначении системной переменной PATH, а также разберемся с вопросом: как добавить путь к исполняемому файлу в системную переменную PATH в операционных системах Windows 10, Windows 8 и Windows 7. Этой публикацией можно пользоваться как простой инструкцией по добавлению значений в переменную PATH для Windows.

Если вам интересна тема компьютерных сетей, то в блоге уже практически закончена первая часть курса по основам компьютерных сетей, можете ознакомиться с ее содержимым. И вот здесь можно получить немного информации о самом курсе.

Что такое переменная Path и зачем она нужна в Windows. Зачем нужно добавлять путь?

PATH – это системная переменная окружения Unix-подобных (например, Linux Mint) операционных систем, а также операционных систем семейства Windows. В переменной PATH нет ничего сложно и хитрого, это обыкновенный список папок и каталогов, в которых лежат исполняемые файлы (программы). Программы, путь к исполняемым файлом которых задан в системной переменной PATH, могут быть исполнены (запущены) непосредственно из командной строки Windows и из любого места вашей файловой системы (в Linux тоже есть командная строка, но ее лучше называть эмулятор терминала).

Давайте лучше посмотрим на примере зачем нужна переменная PATH в операционных системах семейства Windows (как, впрочем, и в других семействах). Смотреть будем на примере сторонней утилиты командной строки Windows tracetcp.exe. Она у меня установлена по следующему пути: c:\Program Files\tracetcp\. Запустим командую строку Windows и попробуем выполнить команду tracetcp.

How to add path to path windows. Смотреть фото How to add path to path windows. Смотреть картинку How to add path to path windows. Картинка про How to add path to path windows. Фото How to add path to path windows

Пробуем запустить стороннюю утилиту командной строки Windows

Обратите внимание на то, что командная строка не смогла выполнить команду tracetcp, хотя приложение и установлено на мой компьютер, проблема заключается в том, что командная строка не смогла найти исполняемый файл tracetcp.exe. Но где командная строка его искала? Она искала этот файл в текущем каталоге, то есть в данном случае в каталоге: c:\Users\Dell, там этого файла не оказалось, затем командная строка обратилась к переменной PATH, там она не обнаружила пути к исполняемому файлу tracetcp.exe, но обнаружила путь к папке System32, проверила, что в этой папке также нет файла tracetcp.exe и выдала нам предупреждение: «»tracetcp» не является внутренней или внешней командой, исполняемой программой или пакетным файлом.».

Поскольку мы находились в папке, отличной от той, где находится файл tracetcp.exe, а пути в переменной PATH к этому файлу не оказалось, командная строка просто не смогла его найти, чтобы исполнить, давайте всё-таки его запустим, для этого нужно будет перейти в папку c:\Program Files\tracetcp при помощи команды cd (в операционных системах Linux тоже есть команда cd и работает она аналогично), а затем запустить утилиту.

How to add path to path windows. Смотреть фото How to add path to path windows. Смотреть картинку How to add path to path windows. Картинка про How to add path to path windows. Фото How to add path to path windows

Запуск исполняемого файла в командной строке Windows

Теперь командная строка Windows смогла запустить нашу утилиту, поскольку смогла найти исполняемый файл tracetcp.exe, но каждый раз переходить в папку, где лежит исполняемый файл или каждый раз указывать абсолютный путь к исполняемому файлу — это очень неудобно, будет гораздо лучше, если мы укажем путь к исполняемому файлу в переменной PATH, тогда командная строка будет самостоятельно его находить в любое время и в любом месте.

How to add path to path windows. Смотреть фото How to add path to path windows. Смотреть картинку How to add path to path windows. Картинка про How to add path to path windows. Фото How to add path to path windows

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

На рисунке выше показано, что командная строка смогла запустить приложение из домашней папки пользователя, но это лишь благодаря тому, что я добавил путь исполняемому файлу в переменную PATH, теперь команда tracetcp будет работать из любой другой папки. Утилита tracetcp довольно простое приложение, представляющее собой один исполняемый файл — tracetcp.exe, можно было бы не прописывать путь в переменную PATH, а просто скопировать этот файл в папку System32, но устанавливать сторонние и непроверенные приложения, не требующие наличия файлов в System32, не самая хорошая и безопасная затея. В Windows лучше потратить немного времени на то, чтобы добавить путь к файлу в переменную PATH, о том как это сделать мы и поговорим ниже, рассмотрев этот процесс для операционных систем Windows 10, Windows 8 и Windows 7.

Как добавить путь к программе в системную переменную Path в Windows 10 и Windows 8

Добавление пути к программе в системную переменную PATH в операционных системах Windows 10 и Windows 8 делается по одному алгоритму, показывать я буду на примере Windows 10, так как восьмерки под рукой нет. Ранее мы уже видели, что небольшая утилита tracetcp запускалась из командной строки Windows только в том случае, если мы переходили в ту папку, в которую она установлена. Но это легко исправить, просто добавив полный путь к исполняемому файлу tracetcp.exe в системную переменную PATH. Давайте это и сделаем. Описывать процесс добавления значения в переменную PATH буду буквально по шагам и с демонстрацией скриншотов окон в Windows 10. Хотя сперва я напишу сам алгоритм, если его не хватит, то обратитесь к скриншотам ниже:

Открываем поиск Windows и в форму пишем: «Система» или «Панель управления». В результате вы должны увидеть примерно такой результат, как показано на рисунке ниже.

How to add path to path windows. Смотреть фото How to add path to path windows. Смотреть картинку How to add path to path windows. Картинка про How to add path to path windows. Фото How to add path to path windows

Используем поиск Windows, ищем по ключевому слову Система

После того, как вы нажмете на кнопку «Система», у вас появится окно, в левой части которого есть небольшое меню, самым нижним пунктом этого меню будет «Дополнительные параметры системы».

How to add path to path windows. Смотреть фото How to add path to path windows. Смотреть картинку How to add path to path windows. Картинка про How to add path to path windows. Фото How to add path to path windows

Чтобы добавить значение в переменную PATH переходим во вкладку Дополнительные параметры системы

После перехода у вас появится окно поменьше, в этом окне нас интересует вкладка «Дополнительно». В правом нижнем углу есть кнопка «Переменные среды. », на нее и нажимаем.

How to add path to path windows. Смотреть фото How to add path to path windows. Смотреть картинку How to add path to path windows. Картинка про How to add path to path windows. Фото How to add path to path windows

Нажимаем на кнопку Переменные среды

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

How to add path to path windows. Смотреть фото How to add path to path windows. Смотреть картинку How to add path to path windows. Картинка про How to add path to path windows. Фото How to add path to path windows

В разделе Системные перемененные ищем переменную PATH

В данном случае нас будет интересовать переменная Path, которая находится в разделе «Системные переменные», кликаем на нее два раза, у нас появляется окно, которое позволяет удалять, добавлять и редактировать значения системной переменной Path в Windows 10 и Windows 8. Нам осталось выполнить два действия: нажать на кнопку создать, в появившуюся активную форму вписать путь к файлу tracetcp.exe и подтвердить свои действия нажатием клавиши «Ок».

How to add path to path windows. Смотреть фото How to add path to path windows. Смотреть картинку How to add path to path windows. Картинка про How to add path to path windows. Фото How to add path to path windows

Дбовляем путь к исполняемому файлу в системную переменную PATH в Windows 10

Закройте все остальные окна. Если у вас была открыта командная строка, вы можете убедиться в том, что она не увидела новое значение переменной PATH, попробуйте выполнить tracetcp из корня диска C, ничего не сработает. Когда вы добавляете новый путь в переменную PATH, программе cmd.exe нужно перечитать значения этой переменной, самый простой способ заключается в том, чтобы закрыть и заново открыть командую строку. Теперь команда tracetcp работает из любой папки, аналогично можно поступать и с другими программами командной строки, которые вы устанавливаете в Windows.

Как настроить переменную Path в Windows 7

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

Как видите, настроить переменную PATH в Windows 7 не так уж и сложно.

Выводы

Вы этой статье мы разобрались с назначение системной переменной PATH и отметили, что в каждой операционной системе оно одинаковое и заключается в том, что переменная PATH является списком каталогов, в котором хранятся исполняемые файлы, если путь к исполняемому файлу есть в переменной PATH, то он может быть исполнен из командной строки операционной системы. Также мы разобрались с тем, как прописать путь к исполняемому файлу в операционных системах Windows 10, 8, 7.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *