Windows cmd which path

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 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 get folder path from file path with CMD

I need path to the folder that contains cmd file. With %0 I can get file name. But how to get folder name?

Читайте также:  Как определить raid windows

P.S. My current directory != folder of the script.

7 Answers 7

For the folder name and drive, you can use:

You can get a lot more information using different modifiers:

This is a copy paste from the «for /?» command on the prompt. Hope it helps.

The accepted answer is helpful, but it isn’t immediately obvious how to retrieve a filename from a path if you are NOT using passed in values. I was able to work this out from this thread, but in case others aren’t so lucky, here is how it is done:

Now the :file_name_from_path function can be used anywhere to retrieve the value, not just for passed in arguments. This can be extremely helpful if the arguments can be passed into the file in an indeterminate order or the path isn’t passed into the file at all.

dp1 for drive and path only. – Andrew Oct 28 ’17 at 1:36

In order to assign these to variables, be sure not to add spaces in front or after the equals sign:

Then you should have no issues.

In case anyone wants an alternative method.

If it is the last subdirectory in the path, you can use this one-liner:

This would return the following:

The . drops back to the previous directory. /ad shows only directories /b is a bare format listing /s includes all subdirectories. This is used to get the full path of the directory to print.

I had same problem in my loop where i wanted to extract zip files in the same directory and then delete the zip file. The problem was that 7z requires the output folder, so i had to obtain the folder path of each file. Here is my solution:

%%i was a full filename path and %ii\.. simply returns the parent folder.

dp1 (etc.) only work on %0, %1, %2 etc. – Artelius Oct 2 ’19 at 4:49

In case the accepted answer by Wadih didn’t work for you, try echo %CD%

Is there an equivalent of ‘which’ on the Windows command line?

As I sometimes have path problems, where one of my own cmd scripts is hidden (shadowed) by another program (earlier on the path), I would like to be able to find the full path to a program on the Windows command line, given just its name.

Is there an equivalent to the UNIX command ‘which’?

On UNIX, which command prints the full path of the given command to easily find and repair these shadowing problems.

26 Answers 26

Windows Server 2003 and later (i.e. anything after Windows XP 32 bit) provide the where.exe program which does some of what which does, though it matches all types of files, not just executable commands. (It does not match built-in shell commands like cd .) It will even accept wildcards, so where nt* finds all files in your %PATH% and current directory whose names start with nt .

Try where /? for help.

Note that Windows PowerShell defines where as an alias for the Where-Object cmdlet, so if you want where.exe , you need to type the full name instead of omitting the .exe extension.

While later versions of Windows have a where command, you can also do this with Windows XP by using the environment variable modifiers, as follows:

You don’t need any extra tools and it’s not limited to PATH since you can substitute any environment variable (in the path format, of course) that you wish to use.

And, if you want one that can handle all the extensions in PATHEXT (as Windows itself does), this one does the trick:

It actually returns all possibilities but you can tweak it quite easily for specific search rules.

Читайте также:  Переключение звуковых дорожек windows media player

$PATH:%i To add it to an alias.bat script that you load everytime you run cmd.exe (put the above script in a new directory called C:\usr\aliases): DOSKEY which=C:\usr\aliases\which.bat $* Then you can make a script to launch cmd.exe with the alias.bat file: cmd.exe /K E:\usr\aliases\alias.bat – Brad T. Apr 25 ’14 at 20:42

Under PowerShell, Get-Command will find executables anywhere in $Env:PATH .

And since powershell let’s you define aliases, which can be defined like so.

PowerShell commands are not just executable files ( .exe , .ps1 , etc). They can also be cmdlets, functions, aliases, custom executable suffixes set in $Env:PATHEXT , etc. Get-Command is able to find and list all of these commands (quite akin to Bash’s type -a foo ). This alone makes it better than where.exe , which.exe , etc which are typically limited to finding just executables.

Finding executables using only part of the name

Finding custom executables

Unlike UNIX, where executables are files with the executable ( +x ) bit set, executables on windows are files present in one of the directories specified in the $PATH env. variable whose filename suffixes are named in the $PATHEXT env. variable (defaults to .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.CPL ).

As Get-Command also honours this env. variable, it can be extended to list custom executables. e.g.

See Get-Command for more options and examples.

In Windows PowerShell:

If you have PowerShell installed (which I recommend), you can use the following command as a rough equivalent (substitute programName for your executable’s name):

The GnuWin32 tools have which , along with a whole slew of other Unix tools.

In Windows CMD which calls where :

Cygwin is a solution. If you don’t mind using a third-party solution, then Cygwin is the way to go.

Cygwin gives you the comfort of *nix in the Windows environment (and you can use it in your Windows command shell, or use a *nix shell of your choice). It gives you a whole host of *nix commands (like which ) for Windows, and you can just include that directory in your PATH .

In PowerShell, it is gcm , which gives formatted information about other commands. If you want to retrieve only path to executable, use .Source .

For instance: gcm git or (gcm git).Source

  • Available for Windows XP.
  • Available since PowerShell 1.0.
  • gcm is an alias of Get-Command cmdlet.
  • Without any parameters, it lists down all the available commands offered by the host shell.
  • You can create a custom alias with Set-Alias which gcm and use it like: (which git).Source .
  • Official docs: https://technet.microsoft.com/en-us/library/ee176842.aspx

I have a function in my PowerShell profile named ‘which’

Here’s what the output looks like:

gold on windows platforms, puts all the nice unix utilities on a standard windows DOS. Been using it for years.

It has a ‘which’ included. Note that it’s case sensitive though.

NB: to install it explode the zip somewhere and add . \UnxUtils\usr\local\wbin\ to your system path env variable.

If you can find a free Pascal compiler, you can compile this. At least it works and shows the algorithm necessary.

Not in stock Windows but it is provided by Services for Unix and there are several simple batch scripts floating around that accomplish the same thing such this this one.

The best version of this I’ve found on Windows is Joseph Newcomer’s «whereis» utility, which is available (with source) from his site.

The article about the development of «whereis» is worth reading.

None of the Win32 ports of Unix which that I could find on the Internet are satistactory, because they all have one or more of these shortcomings:

  • No support for Windows PATHEXT variable. (Which defines the list of extensions implicitely added to each command before scanning the path, and in which order.) (I use a lot of tcl scripts, and no publicly available which tool could find them.)
  • No support for cmd.exe code pages, which makes them display paths with non-ascii characters incorrectly. (I’m very sensitive to that, with the ç in my first name :-))
  • No support for the distinct search rules in cmd.exe and the PowerShell command line. (No publicly available tool will find .ps1 scripts in a PowerShell window, but not in a cmd window!)
Читайте также:  Nero micro для windows 10

So I eventually wrote my own which, that suports all the above correctly.

Урок 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.

Спасибо за внимание. Автор блога Владимир Баталий

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