- Set path from command line
- How to set path from command line?
- Add directory to system path environment variable:
- Default option is not allowed more than ‘2’ time(s)
- Команда SET — работа с переменными среды Windows
- How to set the path and environment variables in Windows
- Setting the path and variables in Windows 10
- Setting the path and variables in Windows 8
- Setting the path and variables in Windows Vista and Windows 7
- Setting the path and variables in Windows 2000 and Windows XP
- What is the default Windows %PATH%?
- Setting path in the MS-DOS and Windows command line
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
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
Команда SET — работа с переменными среды Windows
    Команда SET используется для просмотра и изменения переменных среды окружения в командной строке Windows. Переменные окружения — это переменные, принимаемые значения которых характеризуют среду, в которой выполняется текущая программа — пути системных файлов, сведения об аппаратных средствах, каталоги пользователя и т.п. Значения переменных среды формируются в процессе загрузки Windows, регистрации пользователя в системе, при выполнении отдельных процессов или с помощью команды SET . Для просмотра значения, принимаемого конкретной переменной можно воспользоваться командой :
SET переменная
SET PATH — отобразить значение переменной PATH
Для создания новой переменной, или изменения значения существующей, используется команда :
переменная — Имя переменной среды.
строка — Строка символов, присваиваемая указанной переменной.
SET MyName=Vasya — установить значение переменной MyName
SET path=C:\progs;%path% — изменить значение переменной PATH , добавив в начало строки C:\progs
Значение, принимаемое переменной , доступно для обработки в командных файлах, при использовании ее имени, заключенного в знаки процента — % . Например команда выдачи текста на дисплей ECHO в виде:
ECHO date — выведет на экран слово «date», а команда
ECHO %date% выведет на экран значение переменной date , т.е. текущую дату в формате операционной системы.
Команда SET без параметров используется для вывода текущих значений переменных среды.
ALLUSERSPROFILE=C:\ProgramData
APPDATA=C:\Users\Usr\AppData\Roaming
CommonProgramFiles=C:\Program Files\Common Files
COMPUTERNAME=TEST7
ComSpec=C:\windows\system32\cmd.exe
FP_NO_HOST_CHECK=NO
HOMEDRIVE=C:
HOMEPATH=\Users\Usr
LOCALAPPDATA=C:\Users\Usr\AppData\Local
LOGONSERVER=\\TEST7
NUMBER_OF_PROCESSORS=2
OS=Windows_NT
Path=C:\windows\system32;C:\windows;
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS; .VBE;.JS;.JSE;.WSF;.WSH;.MSC
PROCESSOR_ARCHITECTURE=x86
PROCESSOR_IDENTIFIER=x86 Family 15 Model 3 Stepping 4, GenuineIntel
PROCESSOR_LEVEL=15
PROCESSOR_REVISION=0304
ProgramData=C:\ProgramData
ProgramFiles=C:\Program Files
PROMPT=$P$G
PSModulePath=C:\windows\system32\Windows PowerShell\v1.0\Modules\
PUBLIC=C:\Users\Public
SystemDrive=C:
SystemRoot=C:\windows
TEMP=C:\Users\Usr\AppData \Local\Temp
TMP=C:\Users\Usr\AppData \Local\Temp
USERDOMAIN=test7
USERNAME=Usr
USERPROFILE=C:\Users\Usr
windir=C:\windows
Кроме переменных, отображаемых в списке, при вызове команды SET, существуют и другие, значения которых изменяется динамически:
%CD% — принимает значение текущего каталога.
%DATE% — принимает значение текущей даты.
%TIME% — принимает значение текущего времени.
%RANDOM% — значение случайного числа в диапазоне между 0 и 32767.
%ERRORLEVEL% — текущее значение ERRORLEVEL, специальной переменной, которая используется в качестве признака результата выполнения программы.
%CMDEXTVERSION% значение версии расширенной обработки команд CMD.EXE.
%CMDCMDLINE% — раскрывается в исходную командную строку, которая вызвала командный процессор .
Если при вызове команды SET указать только часть имени, то будет выведен список переменных, имена которых начинаются с указанной строки. Например:
SET U — выведет значения всех переменных, имена которых начинаются с ‘U’.
Команда SET поддерживает два дополнительных ключа:
SET /A выражение
SET /P variable=[promptString]
Ключ /A указывает, что строка справа от знака равенства является числовым выражением, значение которого вычисляется. Обработчик выражений очень прост и поддерживает следующие операции, перечисленные в порядке убывания приоритета:
() * / % + — > & ^ | = , | — группировка — арифметические операторы — арифметические операторы — двоичный сдвиг — двоичное И — двоичное исключающее ИЛИ — двоичное ИЛИ — присвоение — разделитель операторов |
При использовании любых логических или двоичных операторов необходимо заключить строку выражения в кавычки. Любые нечисловые строки в выражении рассматриваются как имена переменных среды, значения которых преобразуются в числовой вид перед использованием. Если переменная с указанным именем не определена в системе, вместо нее подставляется нулевое значение. Это позволяет выполнять арифметические операции со значениями переменных среды, причем не нужно вводить знаки % для получения значений. Если команда SET /A вызывается из командной строки, а не из пакетного файла, она выводит окончательное значение выражения. Слева от любого оператора присваивания должно стоять имя переменной среды. Числовые значения рассматриваются как десятичные, если перед ними не стоит префикс:
0x — для шестнадцатеричных чисел
0 — для восьмеричных чисел.
Пример использования префиксов:
SET /A REZ=0xA+012
ECHO %REZ%
В данном командном файле значение переменной REZ вычисляется сложением числа 10, представленного в шестнадцатеричном виде ( 0xA ) и числа 10 , представленного в восьмеричном ( 012 ).
Ключ /P позволяет установить значение переменной для входной строки, введенной пользователем. Показывает указанное приглашение promptString перед чтением введенной строки. Приглашение promptString может быть пустым. Данный ключ позволяет организовать диалог с пользователем в командном файле:
@ECHO OFF
SET /P NAME=Введите имя пользователя:
SET /P pass=Введите пароль:
ECHO Имя пользователя — %NAME% , Пароль — %PASS%
В командных файлах довольно часто требуется работать с частью значения, принимаемого переменной, для чего используются подстановочные значения:
переменная:строка1=строка2 — заменяет в принимаемом значении переменной строку1 на строку2
Следующий командный файл использует замену символа «точка» на символ «тире» в значении переменной, соответствующем текущей дате:
@ECHO OFF
set tm=%DATE%
ECHO Дата1 = %tm%
SET tm=%DATE:.=-%
ECHO Дата2 = %tm%
Для выделения части значения, принимаемого переменной, используется следующая конструкция:
x,y — где x — число пропускаемых символов от начала строки, а y — количество символов, используемых в качестве значения переменной.
Следующий пример использует отображение текущего времени без секунд и долей секунд (только первые 5 символов из стандартного значения переменной TIME):
@ECHO OFF
set tm=%TIME%
ECHO Время1 = %tm%
SET tm=%TIME:
0,5%
ECHO Время2 = %tm%
Если значение y ( длина ) не указана, то используется оставшееся до конца строки значение переменной. Если значение y отрицательно, то используется часть строки значения переменной от конца. Предыдущий пример можно изменить , указав, что в принимаемом значении времени отбрасываются 6 символов от конца:
@ECHO OFF
set tm=%TIME%
ECHO Время1 = %tm%
SET tm=%TIME:
Возможно использование число пропусков не задано, и используется отрицательное число, то принимаемое значение будет частью переменной от конца строки:
-10% — извлечет последние 10 символов переменной PATH
. Нулевое значение можно не указывать, сохраняя формат подстановки:
0,-2% эквивалентно %PATH:
При использовании переменных окружения в командных файлах существует определенное ограничение, связанное с тем фактом, что присваиваемое значение остается без изменения при его модификации внутри группы команд, задаваемой скобками, например в командах IF или FOR . Для обхода данного ограничения используется запуск командного процессора с параметром /V:ON и вместо знаков процента, для получения принимаемого переменной значения, используются восклицательные знаки. Кроме того, существует возможность использовать стандартный запуск командного процессора, но с локальным включением данного режима командой :
Разница в результатах использования значений переменных довольно наглядно демонстрируется следующим командным файлом:
Setlocal EnableDelayedExpansion
@ECHO OFF
set VAR=before
if «%VAR%» == «before» (
set VAR=after
if «!VAR!» == «after» @echo Со знаком процента=%VAR% , Со знаком вопроса=!VAR!
)
Команда set VAR=after выполняется внутри подпрограммы, ограниченной скобками и, если убрать команду Setlocal EnableDelayedExpansion или не использовать для получения значения переменной VAR восклицательные знаки, ее значение останется старым ( тем, что было установлено до входа в подпрограмму ). Аналогичная же проблема наблюдается и тогда, когда значение переменной изменяется внутри цикла команды FOR . Например, для получения списка файлов текущего каталога такой командный файл не будет работать:
set LIST=
for %%i in (*) do set LIST=%LIST% %%i
echo %LIST%
Значение переменной LIST внутри цикла изменено не будет. Для того, чтобы это произошло, командный файл нужно изменить следующим образом:
Setlocal EnableDelayedExpansion
set LIST=
for %%i in (*) do set LIST=!LIST! %%i
echo %LIST%
Теперь, значение переменной LIST внутри цикла FOR будет изменяться, последовательно принимая значения имен файлов, разделенных пробелом ( set LIST=!LIST! %%i )
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
- From the desktop, right-click the very bottom-left corner of the screen to get the Power User Task Menu.
- From the Power User Task Menu, click System.
- In the Settings window, scroll down to the Related settings section and click the System info link.
- In the System window, click the Advanced system settings link in the left navigation pane.
- In the System Properties window, click the Advanced tab, then click the Environment Variablesbutton near the bottom of that tab.
- 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
- From the desktop, right-click the very bottom-left corner of the screen to get the Power User Task Menu.
- From the Power User Task Menu, click System.
- Click the Advanced System Settings link in the left column.
- In the System Properties window, click the Advanced tab, then click the Environment Variablesbutton near the bottom of that tab.
- 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
- 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.
- Click the Advanced System Settings link in the left column.
- In the System Properties window, click the Advanced tab, then click the Environment Variablesbutton near the bottom of that tab.
- 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 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.
- 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.
- In the System Propertieswindow, click the Advancedtab.
- In the Advanced section, click the Environment Variablesbutton.
- 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.