Windows set env path

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.

Читайте также:  Потемнел экран монитора компьютера что делать windows 10

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

How to set PATH environment variable in batch file only once on Windows?

I have batch file that sets user path and is run as part of Visual Studio IDE build step.

When I build the project, close VS, and reopen it, and rebuild, I see appended path as part of PATH variable. However, I see that in Windows setting of environment variable PATH variable is created under user environment variables as

Question 1:

Why does this path also appear as appended path as part of system environment variable?

On executing echo %PATH% through Visual Studio console (when I run the project second times) prints system variable path and the new path I created appended to it.

Question 2:

I want to modify my batch file so that it only sets once PATH environment variable in user settings during first run of Visual Studio build. If the user variable PATH already exists on subsequent runs, it should not execute set command again to avoid appending new path again and again in system variable.

Any ideas how to achieve this?

2 Answers 2

edit: After some testing, it appears that my original answer isn’t entirely applicable to OP’s questions. To answer OP more directly:

%PATH% combines the values in HKLM\System\CurrentControlSet\Control\Session Manager\Environment\Path with HKCU\Environment\Path . When you setx «dir;dir» , what you’re setting is the HKEY_CURRENT_USER Path value. The machine-wide HKEY_LOCAL_MACHINE Path value remains untouched. That’s why you see your values as appended, rather than as replacements. You’d have to use setx /m to replace the HKLM Path value. But please don’t unless you want to create severe problems with your operating system installation.

If you want to test whether a directory exists in %PATH% , you could cd or pushd both to the directory you want to check and to each directory within %PATH% to unify each, making sure all relative paths, environment variables, etc. are flattened. set «var=%CD%» for each. Then if /I «!dir1!»==»!dir2!» the directory already exists somewhere in %PATH% . There’s an example of this in my original answer below.

The reason my original answer isn’t entirely applicable is because setx itself isn’t as destructive as I once thought. The danger is that often times when users want to append a directory to their path, they’ll setx /m PATH «%PATH%;new dir» ; and that is destructive. Because %PATH% is expanded before setx writes the value, all the directories in PATH are expanded prematurely.

The following method would be safer:

But that wasn’t really what OP asked, and I apologize for the knee-jerk answer.

original answer: setx is destructive and shouldn’t be used this way. When you setx PATH you’re converting the registry value data type from REG_EXPAND_SZ to REG_SZ. As soon as you do this, all the dynamic environment variables stored in your %PATH% get converted to flat, absolute paths. Use the path command to append directories to your %PATH% temporarily, and reg add to do so permanently. (As a side note, there’s also dpath , which temporarily adds a directory to your path, but can only be used by the type command. Scroll 2/3 the way down this page for more info on dpath .)

Читайте также:  Astra linux ldap client

How do I set system environment variables in Windows 10? [duplicate]

How do I set a system environment variable in Windows 10 (without using the registry editor)?

(Note: Other answers don’t specifically address Windows 10 — at least not yet — and they leave off important steps — like how to open the control panel — that changed since previous versions of Windows.)

9 Answers 9

Update: After seeing lots of comments about setting environment variables without admin in Windows 10, I think I have found a way. I was not admin and could use PowerShell.

PowerShell method

You can list all environment variables with: Get-ChildItem Env: .

To get the value of a specific variable: $Env:PATH , where PATH is the name of the variable.

To set a variable: [Environment]::SetEnvironmentVariable(«PATH», «C:\TestPath», «User») , the first parameter is the name of the variable, the second is the value, the third is the level of.

There are different ways to work with environment variables and certain quirks with them in PowerShell so consult the link for details.

Old method (no longer available in newer Windows 10 updates, use PowerShell or see other answers)

Go into Settings and click on System.

Then on the left side click About and select System info at the bottom.

In the new Control Panel window that opens, click Advanced system settings on the left.

Now in the new window that comes up, select Environment Variables. at the bottom.

Still the same as ever: It’s in the old-style control panel’s “System” thingy. You can reach it with Win Break or by right-clicking the Start button.

From there, select “Advanced system settings” → “Environment Variables”.

Or you can do it the hard way and find some other entry point to the old-style control panel, like the Network and Sharing Center or the Desktop folder(!).

I typed «envir» in the «Search the web and Windows» box and selected «Edit environment variables for your account» under the «Best Match»

If by «system environment variables» you refer specifically to system-wide environment variables, then other answers have already covered this. However, if you want to edit both system-wide and user-specific environment variables then most (if not all) of these answers are inapplicable in general case.

Going through «System» and then “Advanced system settings” -> “Environment Variables” will only work for accounts from Administrators group, because only such accounts have access to “Advanced system settings”.

If you attempt do that from a regular user account, then trying to access “Advanced system settings” will trigger an UAC prompt asking you for administrator password. If you enter the password, “Advanced system settings” will successfully open, but any user-specific changes you make there will apply to the corresponding administrator’s account (!), not to your original user’s account.

In order to solve this problem (i.e. in order to give regular users the opportunity to edit their own environment variables) Windows provides another way to access the “Environment Variables” dialog.

Open Control Panel. Open User Accounts applet. On the left-hand side of that applet you will see a link that says Change my environment variables. Click that link, and it will take you to the same “Environment Variables” dialog for your user’s environment variables.

If your user has administrator rights, you will be able to edit both sections of that dialog: user-specific environment variables (upper section) and system-wide environment variables (lower section). If you don’t have administrator rights, you will only be able to edit the upper section: your own user-specific environment variables.

This is the proper way to edit environment variables in all post-UAC versions of Windows, not what is suggested in the majority of the answers above.

Unfortunately, Windows 10 November update (version 1511) destroyed this functionality. The Change my environment variables link no longer works. It is there, but it is dead. So for the post-November version of Windows 10 the correct answer is: it is generally impossible to edit user-specific environment variables in version 1511 of Windows 10 from regular user accounts. Microsoft has destroyed Windows 10 with this update and Windows 10 is now unusable. It will remain the case until they fix these ridiculous bugs in 1511 version of the OS.

Читайте также:  Linux check cpu frequency

For the time being one workaround for non-administrative accounts is to, well, add your user account to Administrators group, logout, log back in, edit the variables using «System» -> “Advanced system settings” method, and then take away administrative rights again.

An alternative workaround is to use PowerShell features as described here https://technet.microsoft.com/en-us/library/ff730964.aspx

Windows 10 Anniversary Update (version 1607) released August 2, 2016 finally fixed this bug.

Системная переменная окружения PATH в Windows

Если Вам нужно настроить PATH в Linux — перейдите сюда

↓ Содержание статьи ↓

Для чего используется
Пример
Добавить директорию в PATH
Изучить содержимое PATH
Ошибки
Postgesql

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

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

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

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

Пример

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

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

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

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

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

Быстрый способ перейти к редактированию PATH — нажать клавишу Win и ввести в поиск env

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

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

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

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

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

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

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

C:\Program Files (x86)\Mozilla Firefox

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

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

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

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

Name Value —- —— Path C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPo.

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

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

Ошибки

-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 `(‘

Для решения этой проблемы Вам нужно экранировать пробелы и скобки. Если импортируется много путей и ввод очень длинный — немного проще записать PATH=$PATH:/путь , если Вам подходит запись в конец.

Также нужно помнить, что все лишние пробелы сломают импорт — для проверки можно сделать весь скрипт в одну строку в текстовом редакторе.

Также стоит помнить, что если Вы работаете в bash под Windows , то переменные окружения нужно задавать через Windows.

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

Postgesql

Приведу пример для использования psql из bash под Windows — это может пригодиться если Вы хотите временно добавить путь к psql в PATH чтобы запустить Postrgres скрипт.

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

Похожие статьи:

Если остались вопросы — смело задавайте их в Telegram группе — aofeedchat либо воспользуйтесь поиском по сайту

Чтобы следить за выходом новых статей — подписывайтесь на Telegram канал aofeed

Оцените статью