On the System dialog page, you’ll see an Advanced system settings link on the left-hand side.
This will bring up the System Properties dialog, which should already be open to the Advanced tab. Go ahead and click on the Environment Variables button at the very bottom.
On the Environment Variables dialog, you’ll see two sets of variables: one for user variables and the other for system variables. Both lists have the PATH variable, so you have to decide which one to edit.
If you only need the commands for your own user account, then edit the user variable. If you need it to work across the computer system regardless of which user is logged in, then edit the system variable. Click on Path and then click on Edit.
On the Edit environment variable dialog, you’ll see a list of all the paths that are currently in the PATH variable. As you can see, Node.js and Git already added their paths so that I can run Git commands and Node.js commands from anywhere while in the command prompt.
To add a new path, simply click on New and it’ll add a new line to the bottom of the list. If you know the path, simply type it in or copy and paste it. If you prefer, you can also click Browse and then navigate to the desired path.
To edit any path, simply select it and then click on the Edit button. You can also delete paths using the Delete button. Note that you can also move items up and down on the list. When you type a command at the command prompt, Windows has to search through each directory stored in the PATH variable to see if that executable exists or not. If you want your executable to be found faster, just move that path up to the top of the list.
This can also come in handy if you have multiple versions of the same command in different paths and need to have one run instead of the other. The one that shows up higher in the list will be run when you type in the command.
Lastly, if you click on Edit text, it will load a dialog where you can edit the Path variable using the old interface where all the paths are listed in one text box.
That’s all there is to it! If you want to learn more about environment variables, make sure to check out my post on how to create your own custom environment variables. Enjoy!
Founder of Help Desk Geek and managing editor. He began blogging in 2007 and quit his job in 2010 to blog full-time. He has over 15 years of industry experience in IT and holds several technical certifications. Read Aseem’s Full Bio
Как запустить программу из командной строки не переходя каждый раз в папку с программой?! Как запускать сторонние программы так, как, например, программу IPCONFIG, которая не требует перехода в папку?
Если вы скачали программу командной строки, например ADB (Android Debuggin Bridge), то вы не сможете запустить ее просто вписав adb в командной строке, как вы всегда поступали с системными командами Windows (IPCONFIG, NETSTAT и т.п.). Вместо этого вы должны будете указать командную строку содержащую полный путь к exe-файлу.
Это достаточно сложно писать в командной строке без ошибок, тем более, если вам приходится делать это достаточно часто.
PATH система Windows сообщает вашей операционной системе каталоги, в которых следует искать исполняемые файлы. Например ранее упоминаемая программа ipconfig.exe расположена в каталоге C:\Windows\System32, который в свою очередь уже добавлен в PATH Windows. При вводе команды ipconfig система обыщет все папки из PATH на наличие файла ipconfig.exe и запустит его выполнение.
Если вы хотите то же удобство с программой (в нашем примере это ADB), то приложение ADB необходимо добавить в PATH Windows и после этого для запуска достаточно будет вписать в командную строку:
Больше ничего впечатывать не придется.
В Windows 7, 8 и Windows 10 попасть в настройки PATH можно так: Панель управления / Система / Дополнительные переменные среды.
Далее перейти в «Переменные среды».
В окне «Переменные среды» обратите внимание на переменную с именем Path. Выберите ее и нажмите «Изменить..»
Дальнейшие действия одинаковы в Windows 7 и 8, но иные, облегченные, в Windows 10.
В этих системах переменная Path является не более, чем длинной строкой текста с адресами каталогов системы. В этот текст мы добавим каталог и с нашей программой ADB.
Для того, чтобы добавить запись с путем к исполняемому файлу в Windows 7 и 8 к тексту нужно добавить путь, которому предшествует точка с запятой, разделяющая различные записи. Например так:
Добавлять такой путь в текст path нужно только в конец строки.
После ввода нажмите ОК. Все, мы добавили каталог в patch Windows 7 и 8.
В операционной системе Windows 10 этот процесс проще и менее запутанный. После нажатия кнопки «Изменить…» откроется новое диалоговое окно с расположенными в отдельных строках путях path.
Это улучшение позволяет проще и нагляднее видеть имеющиеся пути path и облегчает добавить новые пути.
Для добавления нового пути в переменную path Windows 10 нужно нажать «Новый», добавить путь C:\Android\platform-tools и нажать ОК.
Новая запись появится в низу списка.
Теперь запуск Android Debug Bridge доступен из любого раздела командной строкой без ввода полного пути к исполняемому файлу.
в операционных системах Windows NT я попытался добавить этот каталог в свою систему PATH переменные среды:
поэтому я добавил этот каталог с помощью «Мой Компьютер» > «Свойства» > «дополнительно» > «Переменные среды» > «путь». Я сохранил его, но когда я набрал:
на моей консоли он не показывает никаких добавленных «C:xamppphp-каталог
у меня есть два вопроса:
почему это произошло? Быть там что-то я сделал не так?
как я могу добавить каталоги в моем PATH переменная с помощью консоли или программно (через пакетный файл)?
Это только изменяет реестр. Процесс не будет использовать эти значения, пока он не будет запущен после это изменение и не наследует природу своих родителей.
вы не указали, как вы начали сеанс консоли. Лучший способ убедиться в этом-выйти из системы и снова войти в систему.
в открывшемся окне команд.
в семействе Windows 8 (8 & 8.1), вы должны запустить командную строку с правами администратора.
из-за использования %PATH% переменная, эта команда объединит системные переменные среды с пользовательскими.
вам не нужны set или setx команда, просто откройте терминал и введите:
это показывает текущее значение переменной PATH. Теперь вы хотите добавить в каталог? Просто введите:
если по какой-либо причине вы хотите очистить переменную PATH (нет путей вообще или удалить все пути в ней), введите:
обновление
как Даниал Уилсон отметил в комментарии ниже, он устанавливает путь только в текущем сессия. Для установки пути постоянно используйте setx но имейте в виду, хотя это устанавливает путь постоянно, но не в текущем сеансе, поэтому вам нужно запустить новую командную строку, чтобы увидеть изменения, подробнее здесь.
чтобы проверить, существует ли переменная среды или увидеть ее значение, используйте ECHO commnad:
в этот век PowerShell я бы редактировал путь так:
чтобы установить переменную для всех пользователей, в масштабе всей машины, последняя строка должна быть такой:
в скрипте PowerShell, вы, возможно, захотите, чтобы проверить наличие вашего C:\xampp\php перед добавлением в PATH (в случае, если он был ранее добавлен). Вы можете обернуть его в if условное.
Итак, собирая все это вместе:
edit: согласно комментарию-работает со стандартным Windows cmd, но не в powershell.
для powershell the %CD% эквивалентной [System.Environment]::CurrentDirectory
The ss64 SETX страница есть несколько очень хороших примеров. Важно отметить, что это указывает на то, где ключи реестра для SETX vs SETX /M
(это в основном то же самое, за исключением другого Key и SETX /M модификатор)
наконец, есть потенциально улучшенная версия под названием SETENV рекомендуется на странице ss64 SETX, которая разбивает настройку переменных среды пользователя или системы.
Что делать, если вы ошиблись путь с помощью setx? Лучший способ-просто через windows U. I. Панель Управления->Все Элементы Панели Управления->Система->Расширенные Настройки Системы->Переменные Среды
прокрутите вниз до Пути и выберите Изменить. Вы также можете скопировать и вставить его в свой любимый редактор, чтобы вы могли видеть весь путь и более легко редактировать его.
для переопределения уже включены исполняемые файлы;
помимо всех ответов, если вы хотите хороший графический инструмент для редактирования переменных среды windows, вы можете использовать Быстрый Редактор Среды
попробуйте! его безопасно использовать и потрясающе!
по пункту 2 Я использую простой пакетный файл, который заполняет PATH или другие переменные окружения для меня. Таким образом, загрязнение переменных среды по умолчанию отсутствует. Этот пакетный файл доступен отовсюду, поэтому я могу ввести:
Вы можете проверить более подробную информацию об этом простой подход здесь.
С другой стороны, использование команды SETX с правами администратора-это путь более мощный, он изменяет эти значения навсегда (или, по крайней мере, до следующего использования этой команды или до следующего манипулирования этими значениями вручную GUI. ).
но для ясности я подумал, что совместное использование здесь лучшее использование синтаксиса SETX это сработало для меня может помочь кому-то однажды:
где любой знак равенства ‘ = ‘ следует избегать, и не беспокойтесь пространства! нет необходимости вставлять дополнительные кавычки для пути что содержит пробелы внутри него-знак разделения’; ‘ выполняйте задание.
ключевое слово PATH, которое следует за SETX, определяет, какой набор значений должен быть изменен среди возможных значений переменных среды системы, а %PATH% (путь слова, окруженный знаком процента) внутри кавычек, говорит ОС оставить существующие значения пути как они есть и добавить следующий путь (тот, который следует за знаком разделения ‘;’ ) к существующим значениям.
лучшей альтернативой панели управления является использование этой бесплатной программы из sourceforge под названием Pathenator:
однако, это только РАБОЧИЕ для системы, которая имеет Dot.Net 4.0 или выше, такие как windows 7,8 или 10.
это общий reg-файл. Скопируйте приведенные ниже строки в новый текстовый документ и сохраните его как anyname.рег. Отредактируйте его с помощью своих программ или документов.
в пути используйте \ для разделения имен папок в ключевых путях, поскольку regedit использует один \ для разделения его ключевых имен. Все reg файлы начинаются с REGEDIT4. Точка с запятой превращает строку в комментарий. Символ @ означает присвоение значения ключу, а не именованному значению.
файл не должен существовать. Это может быть использовано для набора слова.exe, чтобы открыть Winword.исполняемый.
введя start batchfile начнется iexplore.исполняемый.
вам уже говорили о пути в другом ответе. Также смотрите doskey /? для cmd макросов (они работают только при вводе).
вы можете запускать команды запуска для CMD. Из Windows Recource Kit Техническая Справка
Автозагрузка
описание
содержит команды, которые выполняются при каждом запуске Cmd.исполняемый.
This is what I did:
The path is correct, I checked it 1000 times.
I think you are editing something in the windows registry but that has no effect on the path.
the variable of interest is the PATH
also you can type on the command line:
Another method that worked for me on Windows 7 that did not require administrative privileges:
Click on the Start menu, search for «environment,» click «Edit environment variables for your account.»
In the window that opens, select «PATH» under «User variables for username» and click the «Edit. » button. Add your new path to the end of the existing Path, separated by a semi-colon ( %PATH%;C:\Python27;. ;C:\NewPath ). Click OK on all the windows, open a new CMD window, and test the new variable.
I founded the problem: Just insert the folder without the executable file.
so Instead of:
you have to write this:
In answer to the OP:
The PATH environment variable specifies which folders Windows will search in, in order to find such files as executable programs or DLLs. To make your Windows installation find your program, you specify the folder that the program resides in, NOT the program file itself!
So, if you want Windows to look for executables (or other desired files) in the folder:
because, for example, you want to install PHP manually, and choose that folder into which to install PHP, then you add the entry:
to your PATH environment variable, NOT an entry such as «C:\PHP\php.exe».
Once you’ve added the folder entry to your PATH environment variable, Windows will search that folder, and will execute ANY named executable file you specify, if that file happens to reside in that folder, just the same as with all the other existing PATH entries.
Before editing your PATH variable, though, protect yourself against foul ups in advance. Copy the existing value of the PATH variable to a Notepad file, and save it as a backup. If you make a mistake editing PATH, you can simply revert to the previous version with ease if you take this step.
Your PATH environment variable is a text string, consisting of a list of folder paths, each entry separated by semicolons. An example has already been given by someone else above, such as:
Your exact version may vary depending upon your system.
So, to add «C:\PHP» to the above, you change it to read as follows:
Then you copy & paste that text into the windows dialogue box, click OK, and you should now have a new PATH variable, ready to roll. If your changes don’t take effect immediately, you can always restart the computer.
I am trying to add C:\xampp\php to my system PATH environment variable in Windows.
I have already added it using the Environment Variables dialog box.
But when I type into my console:
it doesn’t show the new C:\xampp\php directory:
I have two questions:
This only modifies the registry. An existing process won’t use these values. A new process will do so if it is started after this change and doesn’t inherit the old environment from its parent.
You didn’t specify how you started the console session. The best way to ensure this is to exit the command shell and run it again. It should then inherit the updated PATH environment variable.
After you change PATH with the GUI, close and re-open the console window.
Execute this command in the command window you have open:
WARNING: This solution may be destructive to your PATH, and the stability of your system. As a side effect, it will merge your user and system PATH, and truncate PATH to 1024 characters. The effect of this command is irreversible. Make a backup of PATH first. See the comments for more information.
Don’t blindly copy-and-paste this. Use with caution.
You can permanently add a path to PATH with the setx command:
You should run this command from an elevated command prompt.
If you only want to change it for the current session, use set.
You don’t need any set or setx command. Simply open the terminal and type:
This shows the current value of PATH variable. Now you want to add directory to it? Simply type:
If for any reason you want to clear the PATH variable (no paths at all or delete all paths in it), type:
Update
Like Danial Wilson noted in comment below, it sets the path only in the current session. To set the path permanently, use setx but be aware, although that sets the path permanently, but not in the current session, so you have to start a new command line to see the changes. More information is here.
To check if an environmental variable exist or see its value, use the ECHO command:
I would use PowerShell instead!
To add a directory to PATH using PowerShell, do the following:
To set the variable for all users, machine-wide, the last line should be like:
In a PowerShell script, you might want to check for the presence of your C:\xampp\php before adding to PATH (in case it has been previously added). You can wrap it in an if conditional.
So putting it all together:
Better still, one could create a generic function. Just supply the directory you wish to add:
You could make things better by doing some polishing. For example, using Test-Path to confirm that your directory actually exists.
The ss64 SETX page has some very good examples. Importantly it points to where the registry keys are for SETX vs SETX /M
(It’s basically the same except with a different Key and the SETX /M modifier.)
Finally there’s potentially an improved version called SETENV recommended by the ss64 SETX page that splits out setting the user or system environment variables.
1. Not strictly true
Handy if you are already in the directory you want to add to PATH:
It works with the standard Windows cmd, but not in PowerShell.
To override already included executables;
Aside from all the answers, if you want a nice GUI tool to edit your Windows environment variables you can use Rapid Environment Editor.
Try it! It’s safe to use and is awesome!
It does things in an intuitive way. For example:
It shows results without the need to spawn a new cmd!
Regarding point 2 I’m using a simple batch file that is populating PATH or other environment variables for me. Therefore, there is no pollution of environment variables by default. This batch file is accessible from everywhere so I can type:
Checking the above suggestions on Windows 10 LTSB, and with a glimpse on the «help» outlines (that can be viewed when typing ‘command /?’ on the cmd), brought me to the conclusion that the PATH command changes the system environment variable Path values only for the current session, but after reboot all the values reset to their default- just as they were prior to using the PATH command.
On the other hand using the SETX command with administrative privileges is way more powerful. It changes those values for good (or at least until the next time this command is used or until next time those values are manually GUI manipulated. ).
The best SETX syntax usage that worked for me:
The PATH keyword that follows the SETX defines which set of values should be changed among the System Environment Variables possible values, and the %PATH% (the word PATH surrounded by the percent sign) inside the quotation marks, tells the OS to leave the existing PATH values as they are and add the following path (the one that follows the split sign ‘;’) to the existing values.