- PATH – отобразить или изменить пути поиска исполняемых файлов.
- Windows CMD: Переменная PATH — Добавить PATH — Echo PATH
- Вывод Переменной Windows PATH
- Добавить Путь к Windows PATH
- Задать Windows PATH для Текущей Сессии
- Задать Windows PATH на Постоянной Основе
- Windows cmd find executable path
- Permanent Changes
- PathExt
- Dpath
- Terminology — filename, path, pathname
- Paths for GUI Windows applications
- Errorlevels
- find path of current folder — cmd
- 3 Answers 3
- How do I find the location of an executable in Windows?
- 14 Answers 14
- Example
- Output:
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, карты памяти и т.п.)
Windows CMD: Переменная PATH — Добавить PATH — Echo PATH
PATH — переменная окружения, в которой перечисляется набор директорий, разделенных точкой с запятой ( ; ), в которых расположены исполняемые программы.
В этой заметке я показываю, как вывести содержимое переменной окружения PATH с помощью командной строки в Windows.
Я также показываю, как добавить путь к переменной PATH на постоянной основе или только для текущей сессии.
Дельный Совет: Отображение списка переменных в Windows! Read More →
Вывод Переменной Windows PATH
Вывести содержимое переменной PATH из Windows cmd :
Приведенные выше команды возвращают все пути, которые хранятся в переменной окружения Windows PATH одной строкой, разделенной точкой с запятой ( ; ), что не очень удобочитаемо.
Чтобы вывести каждую запись переменной Windows PATH с новой строки, выполните следующее:
Дельный Совет: Создание переменных окружения в Windows! Читать далее →
Добавить Путь к Windows PATH
Внимание! Это решение может быть деструктивным, так как Windows обрезает PATH до 1024 символов. Перед любыми изменениями обязательно сделайте резервную копию PATH .
Сохраните содержимое переменной окружения Windows PATH в файл C:\path-backup.txt :
Задать Windows PATH для Текущей Сессии
Задать переменную Windows PATH для текущей сессии:
Задать Windows PATH на Постоянной Основе
Запуск от Имени Администратора: Команда setx доступна только начиная с Windows 7 и требует командной строки с повышенными правами.
Добавить каталог к пользовательской переменной PATH на постоянной основе:
Добавить каталог к системной переменной PATH на постоянной основе (для всех пользователей):
Info: Чтобы увидеть изменения после выполнения команда setx — откройте новую командную строку.
Windows cmd find executable path
Display or set a search path for executable files at the command line.
PATH without parameters will display the current path.
The %PATH% environment variable contains a list of folders. When a command is issued at the CMD prompt, the operating system will first look for an executable file in the current folder, if not found it will scan %PATH% to find it.
Use the PATH command to display or change the list of folders stored in the %PATH% environment variable
The PATH environment variable doesn’t use spaces to separate directories. It uses semicolons: ;
You do not need to surround each part of the path with double quotes, PATH will automatically treat spaces as part of the filename.
A trailing backslash is accepted but is not required, each part of the PATH is always treated as a directory not a file.
PowerShell in particular will ignore any path node delimited by double quotes.
By default, Windows does not add a semicolon to the end of the path, but some program installers will (incorrectly) do so. This can lead to double semicolons appearing in the path list, creating a NULL node entry.
To view each item in the path on a single line use this:
Or in a batch file:
To add items to the current path, include %PATH% in your new setting:
PATH=%PATH%;C:\Program Files\My Application
Permanent Changes
Changes made using the PATH command are NOT permanent, they apply to the current CMD prompt only and remain only until the CMD window is closed.
To permanently change the PATH use Control Panel > System > Advanced System settings > Environment Variables.
The %PATH% variable is set as both a system and user variable, the 2 values are combined to give the PATH for the currently logged in user. This is explained in full by MS Product Support Article Q100843
[HKLM\System\CurrentControlSet\Control\Session Manager\Environment]
[HKCU\Environment]
Be wary of using commands like SETX to modify the PATH, the User path can be edited, but the System path remains read-only for most users. If you try to delete an old value and add a new one it is very common for the ‘delete’ to fail and the ‘add’ to succeed, resulting in duplicate values being added to the path.
To programatically modify the PATH there are a few traps to consider:
Stray quotation marks or semi-colon delimiters in the current path, Duplicate entries in the user and system paths, also duplicates in either one (Windows does not check or warn about this), the maximum length of the system path (roughly 2 KB or just 7 paths of the maximum 260 characters), and lastly checking for any dependencies in other applications (if the path you are adding or removing could be used by them).
To modify the path to add settings for a single application, one method is to use a second variable:
e.g.
SetX MYAPP «C:\Program Files\My App» -m
Now include the new variable in the path like so . C:\Windows\system32;%MYAPP%
You can now easily change that one variable %MYAPP% at any time in the future and the PATH will reflect the new value.
- Changing a variable in the Control Panel will not affect any CMD prompt that is already open, only new CMD prompts will get the new setting.
- To change a system variable you must have administrator rights
- If your system has an AUTOEXEC.BAT file then any PATH setting in AUTOEXEC.BAT will also be appended to the %PATH% environment variable. This is to provide compatibility with old installation routines which need to set the PATH. All other commands in AUTOEXEC.BAT are ignored.
PathExt
If you start/run an application without a file extension (for example WinWord instead of WinWord.exe) then the PATHEXT environment variable will be read to determine which file extensions to search for and in what order.
The default value for the PATHEXT variable is: .COM;.EXE;.BAT;.CMD
Many would argue that .CMD should have higher priority than the legacy .BAT.
Dpath
DPATH is an undocumented internal utility that allows the TYPE command to read data files in specified directories as if they were in in the current directory. On some OS’s this is also implemented as the now deprecated APPEND command. The list of directories is held in the %DPATH% environment variable which works just like the %PATH% variable, delimited with semicolons (not quotes). Syntax: DPATH pathname [;pathname].
To type any file on the path:
C:\batch\> type win.ini
The system cannot find the file specified.
C:\batch\> dpath %path%
C:\batch\> type win.ini
Terminology — filename, path, pathname
For a file stored as:
C:\Program Files\Windows Media Player\wmplayer.exe
The Filename is:
wmplayer.exe
The File Extension is:
.exe
The Path is:
\Program Files\Windows Media Player\
The Pathname is
C:\Program Files\Windows Media Player\wmplayer.exe
(so Drive + Path + Filename = Pathname)
If a file reference uses only the filename rather than a full pathname, then that will work only if the file is in the current directory or is listed in the PATH.
Paths for GUI Windows applications
Since Windows 95, the App Paths registry subkey is available to provide a location for specific executable filenames. Populating this avoids the need for applications to modify the system PATH environment variable.
The keys can be found in the following two registry locations and full documentation of this is on docs.microsoft.com
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\App Paths
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\App Paths
The filename used in App Paths does not have to match the destination file.
Errorlevels
If the Path was successfully changed %ERRORLEVEL% = unchanged , typically this will be 0 but if a previous command set an errorlevel, that will be preserved (this is a bug).
If Path could not be changed %ERRORLEVEL% = 1
PATH is an internal command.
“If you do not love your job, change it. Instead of pushing paper, push ideas. Instead of sitting down, stand up and be heard. Instead of complaining, contribute. don’t get stuck in a job description” — Microsoft job advert
find path of current folder — cmd
I use this script to find out the current folder with its .bat file:
it doesn’t work correctly, if the path contains spaces(D:\Scripts\All Scripts -> retrieves only D:\Scripts\, if I place in the folder, whose path doesn’t have spaces it retrieves the full path). How can I fix it?
3 Answers 3
2015-03-30: Edited — Missing information has been added
To retrieve the current directory you can use the dynamic %cd% variable that holds the current active directory
This generates a value with a ending backslash for the root directory, and without a backslash for the rest of directories. You can force and ending backslash for any directory with
Or you can use another dynamic variable: %__CD__% that will return the current active directory with an ending backslash.
Also, remember the %cd% variable can have a value directly assigned. In this case, the value returned will not be the current directory, but the assigned value. You can prevent this with a reference to the current directory
Up to windows XP, the %__CD__% variable has the same behaviour. It can be overwritten by the user, but at least from windows 7 (i can’t test it on Vista), any change to the %__CD__% is allowed but when the variable is read, the changed value is ignored and the correct current active directory is retrieved (note: the changed value is still visible using the set command).
BUT all the previous codes will return the current active directory, not the directory where the batch file is stored.
It will return the directory where the batch file is stored, with an ending backslash.
BUT this will fail if in the batch file the shift command has been used
As the arguments to the batch file has been shifted, the %0 reference to the current batch file is lost.
To prevent this, you can retrieve the reference to the batch file before any shifting, or change the syntax to shift /1 to ensure the shift operation will start at the first argument, not affecting the reference to the batch file. If you can not use any of this options, you can retrieve the reference to the current batch file in a call to a subroutine
This approach can also be necessary if when invoked the batch file name is quoted and a full reference is not used (read here).
How do I find the location of an executable in Windows?
I remembered that I used a tool called as where to find locations for any executable programs like this in a console:
Now I cannot find this tool. Not sure if Windows has a build-in tool to do that search?
14 Answers 14
According to the StackOverflow answer at Is there an equivalent of ‘which’ on windows?, where.exe does this on Windows 7 and Windows Server 2003 and later:
Example
Output:
In powershell use where.exe , Get-Command (or its abbreviation gcm ), as where is the default alias for Where-Object .
EDIT: I should have added, if you can’t use the WHERE command from the command prompt, check your PATH variable. (Just use the «path» command.) Make sure C:\Windows\System32 is in your path. That’s where «where.exe» is located.
WHERE is the command you’re looking for! WHERE is like a cross between the UNIX shell built-in «which» and the «locate» command, in that it works for both command executables and regular files.
It’s also somewhat more complex than either of those two, although, in general a simple
It’s different from the «locate» command in that it’s not looking through the entire filesystem. Instead, the default behavior is to look for files in two locations:
- The current directory.
- All of the directories in the PATH variable.
So, any command that you can run directly from a command prompt without specifying the directory, will be found by the WHERE command. (Because any command like that is already in the PATH variable list.)
If you want to search only in the command path variable, you can use:
If, on the other hand, you want to find all copies of a file in a directory tree, you can use:
Finally, WHERE will find commands and any files with an extension from the PATHEXT variable without including the extension. All other files have to be specified either exactly or with wildcards.
Take for example the files «dxdiag.exe» and «dxdiagn.dll». Note the following command and its output:
It succeeds in returning all versions of «dxdiag.exe» because «.exe» is one of the extensions in the PATHEXT variable. (Note: «WHERE dxdiag» would have worked as well, because C:\Windows\System32 is in the PATH variable.)
on the other hand, fails to return any result, because «.dll» is not in PATHEXT.
In this case, look at the result that adding a wildcard gives us:
It successfully returns all versions of dxdiagn.dll.
For more information, use «WHERE /?». Hope this helps!