Windows add user path

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

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?

hi, when i use setx at an administrator command line, it creates a USER variable, NOT the SYSTEM variable. What am i doing wrong? How do i change the SYSTEM path at command prompt? -thx

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.

I used the command setx /M “c:\Options”, and what it does is delete the current one and then puts that one there, all I want is to add the new variable to the current one. -thx

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

Читайте также:  Как убрать время при загрузке windows

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

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 will differ depending on the version of Windows you have on your computer. Choose a link below for your version of Windows.

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

Setting the path and variables in Windows 10

  1. From the desktop, right-click the very bottom-left corner of the screen to get the Power User Task Menu.
  2. From the Power User Task Menu, click System.
  3. In the Settings window, scroll down to the Related settings section and click the System info link.
  4. In the System window, click the Advanced system settings link in the left navigation pane.
  5. In the System Properties window, click the Advanced tab, then click the Environment Variablesbutton near the bottom of that tab.
  6. In the Environment Variables window (pictured below), highlight the Path variable in the System variables section and click the Edit button. Add or modify the path lines with the paths you want the computer to access. Each different directory is separated with a semicolon, as shown below.

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 variable value.

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

Setting the path and variables in Windows 8

  1. From the desktop, right-click the very bottom-left corner of the screen to get the Power User Task Menu.
  2. From the Power User Task Menu, click System.
  3. Click the Advanced System Settings link in the left column.
  4. In the System Properties window, click the Advanced tab, then click the Environment Variablesbutton near the bottom of that tab.
  5. In the Environment Variables window (pictured below), highlight the Path variable in the System variables section and click the Edit button. Add or modify the path lines with the paths you want the computer to access. Each different directory is separated with a semicolon, as shown below.

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 variable value.

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

Setting the path and variables in Windows Vista and Windows 7

  1. From the desktop, right-click the Computer icon and select Properties. If you don’t have a Computer icon on your desktop, click Start, right-click the Computer option in the Start menu, and select Properties.
  2. Click the Advanced System Settings link in the left column.
  3. In the System Properties window, click the Advanced tab, then click the Environment Variablesbutton near the bottom of that tab.
  4. In the Environment Variables window (pictured below), highlight the Path variable in the System variables section and click the Edit button. Add or modify the path lines with the paths you want the computer to access. Each different directory is separated with a semicolon, as shown below.
Читайте также:  Windows утилита для управления дисками 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 Variable value.

To view and set the path in 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.

  1. From the desktop, right-click My Computer and click Properties. If you don’t have a My Computer icon on your desktop, click Start, right-click the My Computer option in the Start menu, and select Properties.
  2. In the System Propertieswindow, click the Advancedtab.
  3. In the Advanced section, click the Environment Variablesbutton.
  4. In the Environment Variables window (as shown below), highlight the Path variable in the System Variable section and click the Edit button. Add or modify the path lines with the paths you want the computer to access. Each different directory is separated with a semicolon, as shown below.

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 Variable value.

To view and set the path in 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 in the Windows command line, use the path command.

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

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

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

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

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

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

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

14 ответов:

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

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

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

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

разбив его вниз:

внимание: не пропустите создание резервной копии перед использованием этого метода
вы можете потерять данные в свой %PATH% , или добавить нерелевантный контент слияние из системных переменных
другими словами, не слепо копировать/вставить это. Используйте с осторожностью.

в Windows 7 и Windows 8 мы можем постоянно установите путь из командной строки с помощью . Чтобы добавить git к «Путь»:

обратите внимание, что эта команда может обрезать путь, который вы передаете, до 1024 символов, теряя что-либо помимо этого. В общем, обязательно используйте cmd.exe , а не command.com . Оба предоставляют командную строку. cmd.exe новее, и у него меньше ограничений. command.com старше; он имеет ограничения, такие как размер пути.

в семействе Windows 8 (8 & 8.1), вы должны запустить командную строку с правами администратора.

из-за использования %PATH% переменная, эта команда объединит системные переменные среды с пользовательскими.

вам не нужны set или setx команда, просто откройте терминал и введите:

это показывает текущее значение переменной PATH. Теперь вы хотите добавить в каталог? Просто введите:

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

обновление

как Даниал Уилсон отметил в комментарии ниже, он устанавливает путь только в текущем сессия. Для установки пути постоянно используйте setx но имейте в виду, хотя это устанавливает путь постоянно, но не в текущем сеансе, поэтому вам нужно запустить новую командную строку, чтобы увидеть изменения, подробнее здесь.

чтобы проверить, существует ли переменная среды или увидеть ее значение, используйте ECHO commnad:

в этот век PowerShell я бы редактировал путь так:

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

в скрипте PowerShell, вы, возможно, захотите, чтобы проверить наличие вашего C:\xampp\php перед добавлением в PATH (в случае, если он был ранее добавлен). Вы можете обернуть его в if условное.

Читайте также:  Расширенный метод восстановления системы windows

Итак, собирая все это вместе:

поздно на вечеринку — но удобно, если вы уже находитесь в каталоге, который хотите добавить в PATH.

edit: согласно комментарию-работает со стандартным Windows cmd, но не в powershell.

для powershell the %CD% эквивалентной [System.Environment]::CurrentDirectory

Безопасный SETX

  • SETX по умолчанию обновит ваш пользователей путь.
  • SETX . /M обновить система путь.
  • %PATH% содержит системный путь с добавлением пользовательского пути

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

  1. резервное копирование PATH — SETX будет усеките ваш мусор длиной более 1024 символов
  2. не называй SETX %PATH%;xxx — добавляет системный путь в путь пользователя
  3. не называй SETX %PATH%;xxx /M — добавляет путь пользователя в системный путь
  4. чрезмерное использование пакетных файлов может привести к слепоте 1

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

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

добавить

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

append_system_path.cmd . должен быть запущен от имени администратора.

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

варианты

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

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

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

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

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

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

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

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

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

проверка вышеуказанных предложений в Windows 10 LTSB и с проблеском на контурах «справка» (которые можно просмотреть при вводе » command/?’on the cmd), привел меня к вывод о том, что команда PATH изменяет значения системных переменных среды Path только для текущего сеанса, но после перезагрузки все значения сбрасываются по умолчанию — так же, как и до использования команды PATH.

С другой стороны, использование команды SETX с правами администратора-это путь более мощный, он изменяет эти значения навсегда (или, по крайней мере, до следующего использования этой команды или до следующего манипулирования этими значениями вручную GUI. ).

но для ясности я подумал, что совместное использование здесь лучшее использование синтаксиса SETX это сработало для меня может помочь кому-то однажды:

где любой знак равенства ‘ = ‘ следует избегать, и не беспокойтесь пространства! нет необходимости вставлять дополнительные кавычки для пути что содержит пробелы внутри него-знак разделения’; ‘ выполняйте задание.

ключевое слово PATH, которое следует за SETX, определяет, какой набор значений должен быть изменен среди возможных значений переменных среды системы, а %PATH% (путь слова, окруженный знаком процента) внутри кавычек, говорит ОС оставить существующие значения пути как они есть и добавить следующий путь (тот, который следует за знаком разделения ‘;’ ) к существующим значениям.

лучшей альтернативой панели управления является использование этой бесплатной программы из sourceforge под названием Pathenator:

однако, это только РАБОЧИЕ для системы, которая имеет Dot.Net 4.0 или выше, такие как windows 7,8 или 10.

в командной строке вы говорите Cmd использовать командную строку проводника, предваряя ее start .

так start Yourbatchname .

обратите внимание, вы должны зарегистрироваться, как если бы его имя batchfile.exe .

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

это общий reg-файл. Скопируйте приведенные ниже строки в новый текстовый документ и сохраните его как anyname.рег. Отредактируйте его с помощью своих программ или документов.

в пути используйте \ для разделения имен папок в ключевых путях, поскольку regedit использует один \ для разделения его ключевых имен. Все reg файлы начинаются с REGEDIT4. Точка с запятой превращает строку в комментарий. Символ @ означает присвоение значения ключу, а не именованному значению.

файл не должен существовать. Это может быть использовано для набора слова.exe, чтобы открыть Winword.исполняемый.

введя start batchfile начнется iexplore.исполняемый.

вам уже говорили о пути в другом ответе. Также смотрите doskey /? для cmd макросов (они работают только при вводе).

вы можете запускать команды запуска для CMD. Из Windows Recource Kit Техническая Справка

Автозагрузка

описание

содержит команды, которые выполняются при каждом запуске Cmd.исполняемый.

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