Add file to path windows

How to Add to Windows PATH Environment Variable

Works for Windows 10 or 7

If you’re a coder or programmer, you probably spend a decent amount of time using the command prompt to execute programs or compile code. In order to complete those tasks, you most likely have to use a command from a library or software package installed (like Python) on your system.

By default, most of these programs will add their own custom shortcuts to the Windows environment variables. The most used environment variable in Windows is probably the PATH variable. It basically allows you to run any executables that are located inside the paths specified in the variable at the command prompt without having to give the full path to the executable.

In this article, I’ll show you how you can add more paths to the Windows PATH variable in case you want to run executables from your own custom directories. It’s worth noting that the procedure below is for Windows 10, but it’s almost exactly the same for Windows 7 also.

Add Directories to PATH Variable

To get started, right-click on the Computer or This PC icon on the desktop and select Properties. If you don’t have that icon on your desktop already, you can add any missing desktop icons easily.

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

Источник

Set path from command line

Users can run an executable from windows command prompt either by giving the absolute path of the file or just by the executable file name. In the latter case, Windows searches for the executable in a list of folders which is configured in environment variables. These environment variables are as below.

1. System path
2. User path

The values of these variables can be checked in system properties( Run sysdm.cpl from Run or computer properties). Initially user specific path environment variable will be empty. Users can add paths of the directories having executables to this variable. Administrators can modify the system path environment variable also.

How to set path from command line?

In Vista, Windows 7 and Windows 8 we can set path from command lineВ using ‘setx’ command.

For example, to add c:\dir1\dir2 to the path variable, we can run the below command.

Alternative way is to use Windows resource kit tools ‘pathman.exe‘. Using this command we can even remove a directory from path variable. See download windows resource kit tools. This works for Windows 7 also.

Add directory to system path environment variable:

Open administrator command prompt
RunВ the below command

Читайте также:  Windows xp tablet pc 2005 edition

Remove path from system path environment variable:
Run the below command from elevated command prompt

Setting user path environment variable

For user environment varlables, admin privileges are not required. We can run the below command to add a directory to user path environment variable.

To remove a directory from user path, you can run the below command.

Default option is not allowed more than ‘2’ time(s)

You get this error if you have not enclosed ‘path’ in double quotes. See the below example for setting the path of firefox.

Now if you move %path% to be in the double quotes

Could a context entry be created for folders, perhaps an extended one… to add to path?

what about a multi-verb option, like copy as path?

Johny Why
Answer: Try add the parameter /M

Hi, is there a way I can add an extra variable instead on deleting the currently one and put a new Variable on the Path.

Nuno, pathman described above does exactly that. You can download the resource tools kit and get it.

setx path “%path%;C:\yourFolder”

To set path for java & javac, can I add the paths to PATH or do I need to create the environment variable JAVA_HOME. I don’t have this defined, but windows does not seem to be able to find java binaries on my system.

You can directly add the folder to PATH. No need to define JAVA_HOME. However, adding JAVA_HOME separately avoids cluttering and helps to easily understand what is added.

hello, can someone plz explain this result? After setting path, it did not change. This was run from an Administrator command-line:

C:\Windows\system32>setx path “C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\ProgramData\chocolatey\bin;D:\Program Files (x86)\Microsoft VS Code\bin”

SUCCESS: Specified value was saved.

C:\Windows\system32>path
PATH=C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\ProgramData\chocolatey\bin;D:\Program Files (x86)\Microsoft VS Code\bin;D:\Program Files (x86)\metapad36;D:\Program Files (x86)\metapad36″ /M

Why won’t this work?

SET EPO = D:\Program Files (x86)\McAfee\ePolicy Orchestrator
PATH = %PATH%;%EPO%\jre\bin;%EPO%\apache2\bin

In windows 10 set path %path%; not working. it’s work like :
setx “%path%;C:\Program Files\CodeBlocks\MinGW\bin”

By unfortunately I deleted my system default path. How could I able to find my system path?

Unfortunately I deleted several files with unremembered path names. This article was useful

The following used to work for me when I am in MSDOS environment. Lately I get error messages such as INCLUDE not found. Why is this so?

Used to work
SET PLL =c:\CL5\PLL
SET PLT =c:\CL5\PLL
SET INCLUDE =c:\CL5\INCLUDE
SET PRG =c:\IMS\PRG
SET LIB =c:\CL5\LIB
SET OBJ =c:\CL5\OBJ
PATH =c:\IMS\EXE;\CL5\BIN;\CL5\NG;\CL5\PLL

pathman is one of many tools of the Windows Server 2003 Resource Kit Tools

Note: The Windows Server 2003 Resource Kit Tools are not supported on 64-bit platforms.

Huh.
When I did that on Windows 10 v1903, using setx, it replaced the USER scope paths with the SYSTEM scope paths.
Now I’m not sure what was in the old user path.
So, uh… Be careful out there.
And if anyone has a solution how to avoid that, please let me know
Thanks

Источник

Добавление каталога в переменную среды PATH в Windows

в операционных системах Windows NT я попытался добавить этот каталог в свою систему PATH переменные среды:

поэтому я добавил этот каталог с помощью «Мой Компьютер» > «Свойства» > «дополнительно» > «Переменные среды» > «путь». Я сохранил его, но когда я набрал:

на моей консоли он не показывает никаких добавленных «C:xamppphp-каталог

у меня есть два вопроса:

почему это произошло? Быть там что-то я сделал не так?

как я могу добавить каталоги в моем PATH переменная с помощью консоли или программно (через пакетный файл)?

14 ответов:

Это только изменяет реестр. Процесс не будет использовать эти значения, пока он не будет запущен после это изменение и не наследует природу своих родителей.

вы не указали, как вы начали сеанс консоли. Лучший способ убедиться в этом-выйти из системы и снова войти в систему.

в открывшемся окне команд.

в семействе 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

Безопасный SETX

предупреждения

The ss64 SETX страница есть несколько очень хороших примеров. Важно отметить, что это указывает на то, где ключи реестра для SETX vs SETX /M

инструкция по применению

добавить

добавить в систему PATH

(это в основном то же самое, за исключением другого Key и SETX /M модификатор)

варианты

наконец, есть потенциально улучшенная версия под названием SETENV рекомендуется на странице ss64 SETX, которая разбивает настройку переменных среды пользователя или системы.

Что делать, если вы ошиблись путь с помощью setx? Лучший способ-просто через windows U. I. Панель Управления->Все Элементы Панели Управления->Система->Расширенные Настройки Системы->Переменные Среды

прокрутите вниз до Пути и выберите Изменить. Вы также можете скопировать и вставить его в свой любимый редактор, чтобы вы могли видеть весь путь и более легко редактировать его.

для переопределения уже включены исполняемые файлы;

помимо всех ответов, если вы хотите хороший графический инструмент для редактирования переменных среды windows, вы можете использовать Быстрый Редактор Среды

попробуйте! его безопасно использовать и потрясающе!

по пункту 2 Я использую простой пакетный файл, который заполняет PATH или другие переменные окружения для меня. Таким образом, загрязнение переменных среды по умолчанию отсутствует. Этот пакетный файл доступен отовсюду, поэтому я могу ввести:

Вы можете проверить более подробную информацию об этом простой подход здесь.

Читайте также:  Windows install on raspberry pi

С другой стороны, использование команды 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.исполняемый.

Источник

Adding a directory to the PATH environment variable in Windows

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:

18 Answers 18

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.

Option 1

After you change PATH with the GUI, close and re-open the console window.

Option 2

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.

Safer SETX

Warnings

The ss64 SETX page has some very good examples. Importantly it points to where the registry keys are for SETX vs SETX /M

Usage instructions

Append to User PATH

Append to System PATH

(It’s basically the same except with a different Key and the SETX /M modifier.)

Alternatives

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.

Читайте также:  Lazymedia deluxe pro для windows

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.

Источник

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:

Then locate the “Environment Variables” button:

Open Environment Variables:

Opening Environment Variables, we see the following:

Editing Environment Variables:

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:

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

Added Path Variable to User Environment Variables:

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.

Источник

Поделиться с друзьями
Советы экспертов и специалистов
Adblock
detector