- PATH – отобразить или изменить пути поиска исполняемых файлов.
- 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)
- Windows CMD: PATH Variable – Add To PATH – Echo PATH
- Echo Windows PATH Variable
- Add To Windows PATH
- Set Windows PATH For The Current Session
- Set Windows PATH Permanently
- What’s the environment variable for the path to the desktop?
- 18 Answers 18
- Урок 4 по CMD — переменные окружения
PATH – отобразить или изменить пути поиска исполняемых файлов.
Команда PATH используется для указания или просмотра путей поиска исполняемых файлов. Пути поиска представляют собой строки, определяющие перечень каталогов файловой системы, в которых находятся исполняемые файлы (файлы с расширением .bat, .cmd, .exe, .vbs и т.п. ), разделенные точкой с запятой ; Например, C:\windows;C:\windows\system32 — определяет пути поиска C:\windows и C:\windows\system32 . Если вы в командной строке набираете program.exe без явного указания пути, то для запуска файла program.exe выполняется его поиск в текущем каталоге, и если он не найден, то в каталоге C:\windows , если и там не найден – в каталоге C:\windows\system32 . Если же исполняемый файл будет в обоих каталогах, то выполнится запуск из того, что определен ранее — C:\windows . Значение переменной среды PATH содержит пути поиска исполняемых файлов определенный на данный момент времени.
Формат командной строки:
PATH ; — очистить путь поиска используемых файлов, ограничив его текущим каталогом.
PATH [[диск:]путь[;. ][;] — установит ь пути поиска исполняемых файлов.
Команда PATH без параметров отображает текущий путь поиска. В командную строку допускается включение переменной %PATH% , задающей прежний путь поиска.
path /? — отобразить подсказку по использованию команды.
path — отобразить пути поиска исполняемых файлов.
path %PATH%;C:\Scripts — добавить путь C:\Scripts в конец существующего списка каталогов для поиска исполняемых файлов.
path C:\scripts;%PATH% — добавить путь C:\Scripts в начало существующего списка каталогов для поиска исполняемых файлов.
При выполнении команды PATH, значение передаваемых ей параметров не анализируется и воспринимается как обычная строка символов, поэтому, например, трижды выполнив команду path C:\scripts;%PATH% вы создадите 3 записи для пути C:\Scripts . Значение переменной PATH, измененное командой действует только на момент текущего сеанса командной строки. Для постоянного изменения системных и пользовательских переменных среды, в том числе, и путей поиска, используется команда SetX . В постоянно действующих путях поиска не стоит указывать каталоги сменных носителей (дискет, CD/DVD, карты памяти и т.п.)
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
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.
What’s the environment variable for the path to the desktop?
I’m writing a Windows batch file and want to copy something to the desktop. I think I can use this:
However, I’m thinking, that’s probably only going to work on an English OS. Is there a way I can do this in a batch file that will work on any internationalized version?
UPDATE
I tried the following batch file:
And got this output:
18 Answers 18
I found that the best solution is to use a vbscript together with the batch file.
Here is the batch file:
Here is findDesktop.vbs file:
There may be other solutions but I personally find this one less hackish.
I tested this on an English PC and also a French PC — it seems to work (Windows XP).
To be safe, you should use the proper APIs in Powershell (or VBScript)
Using PowerShell:
Copy something using Powershell:
Here is a VBScript-example to get the desktop path:
EDIT: Use the accepted answer, this will not work if the default location isn’t being used, for example: The user moved the desktop to another drive like D:\Desktop
At least on Windows XP, Vista and 7 you can use the «%UserProfile%\Desktop» safely.
Windows XP en-US it will expand to «C:\Documents and Settings\YourName\Desktop»
Windows XP pt-BR it will expand to «C:\Documents and Settings\YourName\Desktop»
Windows 7 en-US it will expand to «C:\Users\YourName\Desktop»
Windows 7 pt-BR it will expand to «C:\Usuarios\YourName\Desktop»
On XP you can’t use this to others folders exept for Desktop My documents turning to Meus Documentos and Local Settings to Configuracoes locais Personaly I thinks this is a bad thing when projecting a OS.
KB’s answer to use [Environment]::GetFolderPath(«Desktop») is obviously the official Windows API for doing this.
However, if you’re working interactively at the prompt, or just want something that works on your machine, the tilda (
) character refers to the current user’s home folder. So
/desktop is the user’s desktop folder.
/desktop works, because it can be redirected for roaming profiles. I am in that situation 😉 – oleschri Apr 30 ’13 at 11:39
Not only would that not work for an International version of Windows, it would fail if the user had edited the Registry to make their Desktop folder reside somewhere else. You can query the Registry for the file location using the REG command:
To get this into a variable use something like this:
you could also open a DOS command prompt and execute the set command.
This will give you an idea what environment variables are available on your system.
E.g. — since you where specifically asking for a non-english Windows — heres is an example of my own German Edition (Window7-64bit) :
in windows 7 this returns the desktop path:
If you wish to use the
from within a cmd.exe , you may do so (thanks to MS User Marian Pascalau on this thread)
This is not a solution but I hope it helps: This comes close except that when the KEY = %userprofile%\desktop the copy fails even though zdesktop=%userprofile%\desktop. I think because the embedded %userprofile% is not getting translated.
So it sucessfully parses out the REG key but if the key contains an embedded %var% it doesn’t get translated during the copy command.
I had a similar problem (and VBScript or PowerShell was not an option) and the code I found in this article did not work for me. I had problems with OS versions and language versions. After some experiments I’ve come to this solution:
This code works for me in English and Polish versions of Windows 7 and Windows XP.
The :reparse subroutine allows for delayed expansion of environment variables.
While I realize this is a bit of an older post, I thought this might help people in a similar situation. I made a quick one line VBScript to pull info for whatever special folder you would like (no error checking though) and it works like this:
Create a file «GetShellFolder.vbs» with the following line:
I always make sure to copy cscript.exe (32-bit version) to the same folder as the batch file I am running this from, I will assume you are doing the same (I have had situations where users have somehow removed C:\Windows\system32 from their path, or managed to get rid of cscript.exe, or it’s infected or otherwise doesn’t work).
Now copy the file to be copied to the same folder and create a batch file in there with the following lines:
In the above code you can replace «Desktop» with any valid special folder (Favorites, StartMenu, etc. — the full official list is at https://msdn.microsoft.com/en-us/library/0ea7b5xe%28v=vs.84%29.aspx) and of course with the actual file you want placed there. This saves you from trying to access the registry (which you can’t do as a limited user anyway) and should be simple enough to adapt to multiple applications.
Oh and for those that don’t know the «%
dp0″ is just the directory from which the script is being called. It works for UNC paths as well which makes the batch file using it extremely portable. That specifically ends in a trailing «\» though so it can look a little odd at first glance.
Урок 4 по CMD — переменные окружения
Практически, вся работа с командной строкой (cmd) основывается на переменных окружения. Так, если в консольном окне прописать на выполнение команду, путь к которой отсутствует, то вначале происходит поиск данной команды на внутреннем уровне.
Если окажется, что внутренняя команда с таким именем существует, то произойдет ее вызов. Если же окажется, что внутренней команды с подобным названием нет, то произойдет поиск вначале в текущем каталоге, а уже потом в тех папках, что перечислены в переменной окружения cmd PATH . Если же и в этом случае соответствия не найдено, командная строка вернет ошибку.
Что бы просмотреть содержимое cmd переменной окружения (среды) PATH, достаточно в консольном окне ввести команду path и нажать ENTER.
Видим, что пути отделяются друг от друга точкой с запятой, точка с запятой позволяет командной строке определить, где начинается и заканчивается путь. Вы можете получить содержимое переменной окружения и таким способом:
Командная строка ищет исполняемые файлы в каталогах в порядке, в котором эти каталоги перечислены в пути к командам.
Довольно часто при работе с командной строкой, может понадобиться прописать временный путь к командам:
В данном примере мы добавили к содержимому в переменные окружения cmd %PATH% путь D:\work, и если теперь ввести на выполнение имя программы в каталоге D:\work, то она успешно запустится. Но помните, временный путь действует только в пределах текущего сеанса командной строки.
Следующий пример значимости переменных окружения является расширение исполняемых файлов. Полагаю, вы замечали, что можно просто ввести имя программы, например, notepad или calc в окне командной строки, и она сразу запуститься, при этом, расширение файла указывать не надо. Все расширения исполняемых файлов задаются в переменной окружения %РАТНЕХТ% , что бы их просмотреть, можно ввести:
Как и при поиске пути, поиск в переменной cmd окружения производится с начала, и все имена расширений отделяются точкой с запятой. Нужно понимать, что если вы введете на выполнение команду notepad, а в системном каталоге есть notepad.com и notepad.exe, то произойдет вызов той программы, чье расширение находится первым. Исполняемыми считаются и файлы сценариев (при условии, что расширение сценария присутствует в списке), например, сценарии сервера Windows Script Host.
При желании, можно подшутить над другом – изменить расположение списка расширений так, что бы вначале находилось, ну скажем расширение .vbs, с помощью языка VBScript написать сценарий, который будет выводить диалоговое сообщение “ Ваша система взломана. Все винчестеры будут отформатированы после перезагрузки… ”. Копии сценария сохранить под разными именами, например: regedit.vbs, cmd.vbs, calc.vbs, notepad.vbs, собственно, под теми именами программ, которые любит запускать ваш друг в окне командной строи или через меню Пуск. Сами файлы разместить в системных каталогах, пути к которым прописаны в %PATH%.
Просмотреть все cmd переменные среды и их содержимое, которые доступны в текущем сеансе командной строки можно с помощью команды set, просто введите ее и нажмите Enter.
Можно просмотреть не только через cmd переменные среды и их содержимое, но и через диалоговое окно системы Windows. Для этого войдите в свойства Мой Компьютер, вкладка дополнительно, внизу будет кнопка “Переменные среды”, нажимаем на нее и смотрим, что прописано в системе. В сервере сценариев Windows Script Host есть объект WScript.Shell, у которого в свою очередь присутствует свойство Environment, которое также позволяет получить информацию о переменных средах Windows, а также метод ExpandEnvironmentStrings которому как параметр передается имя среды (например, %path%, %windir%, %pathext%).
Переменные окружения cmd позволяют получить довольно много системной информации, хотя. ее вы смогли увидеть при выполнении команды set.
Спасибо за внимание. Автор блога Владимир Баталий