- Команда WHERE — поиск файлов по шаблону имени.
- Примеры использования команды WHERE.
- Where are the standard Windows prompt commands files?
- 4 Answers 4
- Is there an equivalent of ‘which’ on the Windows command line?
- 26 Answers 26
- Finding executables using only part of the name
- Finding custom executables
- Windows commands
- Prerequisites
- Command shell overview
- Command-line reference A-Z
Команда WHERE — поиск файлов по шаблону имени.
Команда WHERE используется для определения расположения файлов в каталогах операционных систем Windows 7 и старше, имена которых соответствуют задаваемому шаблону поиска, а также, при необходимости — размера, даты и времени их изменения. По умолчанию поиск выполняется в текущем каталоге и в каталогах, определяемых значением переменной среды PATH .
Формат командной строки:
WHERE [/R каталог] [/Q] [/F] [/T] шаблон.
Параметры командной строки:
/R — Рекурсивный поиск и отображение файлов, соответствующих указанному шаблону, начиная с указанного каталога.
/Q — Возврат только кода выхода без отображения списка найденных файлов (тихий режим)
/F — Отображение имен найденных файлов в кавычках.
/T — Отображение размера, даты и времени изменения для всех найденных файлов.
шаблон — Шаблон поиска для искомых файлов. В шаблоне можно использовать подстановочные знаки * и ?. Также можно задавать конструкции «$пер:шаблон» и «путь:шаблон», где «пер» представляет переменную среды, и поиск осуществляется по путям, указанным в переменной среды «пер». Эти конструкции не следует использовать с параметром /R. При поиске к шаблону также добавляются расширения из переменной PATHEXT. Пример: WHERE «c:\windows;c:\windows\system32:*.dll»
/? — Вывод справки по использованию.
WHERE.EXE возвращает код ошибки 0, если поиск был успешным, 1 — если безуспешным, и 2, если возникли ошибки.
Примеры использования команды WHERE.
WHERE /? — выдать краткую справку по использованию команды.
WHERE myfile.doc — найти расположение файла myfile.doc . Поиск выполняется в текущем каталоге и каталогах, имена которых задаются значением переменной PATH
WHERE /T myfile.doc — то же, что и в предыдущем случае, но в результатах поиска отображается размер, дата и время изменения файла.
WHERE /R C:\ myfile.doc — найти расположение файла myfile.doc . Поиск выполняется рекурсивно, начиная с корневого каталога диска C: ( поиск по всему диску C: )
WHERE /R %windir%\system32 *.log — поиск файлов с расширением log начиная с подкаталога system32 системного каталога Windows.
WHERE /R %windir%\system32 *.log > loglist.txt — поиск файлов с расширением log начиная с подкаталога system32 системного каталога Windows с записью результатов в текстовый файл loglist.txt текущего каталога.
WHERE /R C:\ . dir.* — поиск с использованием шаблона, где первые 3 символа имени файла могут быть любыми ( . , следующие 3 символа принимают значение dir и с любым расширением.
where /R C:\windows\system32 *7*.exe — поиск исполняемых файлов, в имени которых содержится символ «7» , начиная с каталога C:\windows\system32
WHERE /R c:\windows *.vbs *.cmd *.bat — поиск файлов сценариев ( скриптов ) — файлов с расширением vbs , cmd и bat начиная с каталога C:\windows
WHERE /Q file1.ext — не отображать результат поиска. При выполнении этой команды будет установлено значение переменной ERRORLEVEL в зависимости от результата поиска:
ERRORLEVEL=0 — файл file1.ext найден.
ERRORLEVEL=1 — файл file1.ext не найден.
ERRORLEVEL=2 — при поиске файла file1.ext возникла ошибка.
Обычно команда WHERE /Q используется в командных файлах, когда в зависимости от результата поиска заданного файла нужно выполнить ту или иную подпрограмму.
Если вы желаете поделиться ссылкой на эту страницу в своей социальной сети, пользуйтесь кнопкой «Поделиться»
Where are the standard Windows prompt commands files?
If I type dir in the command line, I guess it executes a dir.exe hidden somewhere in the system. Is there such a file? Where is it?
4 Answers 4
Dir is an internal command, like cd , copy , and call . This is simply a subroutine of the DOS interpreter that you’re calling.
There are, however, external commands. These commonly reside in C:\Windows\ C:\Windows\System\ C:\Windows\System32 and (if you have 64-bit windows) C:\Windows\SysWOW64\
However, external commands are not limited to these locations. External commands can be called from the directory that you’re working from. (in a newly started DOS shell on Windows 7, this would usually be C:\Users\YourUsername\ ). External commands from other directories can also be called, as long as the directory they’re in are in your PATH environment variable. To see what directories are in your path, use SET PATH .
If you’re going to be needing some utility from a directory, but will have to be traversing to other directories, you can add the folder of the utility to the PATH by using SET PATH=%PATH%;DriveLetter:\Utility\Path\Here\ . This change only affects that DOS window.
I hope that’s new and useful knowledge!
dir is an internal MS-DOS command. Like the other internal commands, it is built into the file named command.com. Wikipedia has a page for the list of DOS commands, and it says:
The command interpreter for MS DOS runs when no application programs are running; after an application exits, if the memory used for the command interpreter was overwritten, MS DOS will re-load the command interpreter from disk storage. The command interpreter is usually stored in a file called «COMMAND.COM«. Some commands are built-into COMMAND.COM. When the user types a line of text at the operating system command prompt, COMMAND.COM will parse the line, and attempt to match a command name to a built-in command or to the name of an excecutable program file or batch file on disk. If no match is found, an error message is printed and the command prompt is refreshed.
Resident commands varied slightly between revisions of MS DOS. Typically, the functions DIR (list directory), ERASE or DEL (erase a file or directory), COPY (copy files), DATE (display or set date), TIME (display or set time), CD (change working directory), MD (make a directory on the current disk), REN (rename a file or directory) and some others were resident in COMMAND.COM.
To make my answer complete, the following is a list of MS-DOS internal and external commands. The internal commands reside in COMMAND.COM, which loads into memory when the computer system is started; these commands do not reside on disk. The external commands are files that do reside on disk and have an extension of .COM, .EXE, or .BAT. Both command types are executed from the MS-DOS prompt.
Internal Commands:
External Commands:
- APPEND.EXE
- ASSIGN.COM
- ATTRIB.EXE
- BACKUP.EXE
- CHKDSK.EXE
- COMMAND.COM
- COMP.EXE
- DEBUG.EXE
- DISKCOMP.COM
- DISKCOPY.COM
- DOSKEY.COM
- DOSSHELL.COM
- EDIT.COM
- EDLIN.EXE
- EMM386.EXE
- EXE2BIN.EXE
- EXPAND.EXE
- FASTOPEN.EXE
- FC.EXE
- FDISK.EXE
- FORMAT.COM
- GRAFTABLE.COM
- GRAPHICS.COM
- HELP.EXE
- JOIN.EXE
- KEYB.COM
- LABEL.EXE
- MEM.EXE
- MIRROR.COM
- MODE.COM
- MORE.COM
- NLSFUNC.EXE
- PRINT.EXE
- QBASIC.EXE
- RECOVER.EXE
- REPLACE.EXE
- RESTORE.EXE
- SETVER.EXE
- SHARE.EXE
- SORT.EXE
- SUBST.EXE
- SYS.COM
- TREE.COM
- UNDELETE.EXE
- UNFORMAT.COM
- XCOPY.EXE
Nota bene: The external commands reside in C:\Windows\System32 assuming the root drive is C: .
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.
$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!)
So I eventually wrote my own which, that suports all the above correctly.
Windows commands
All supported versions of Windows (server and client) have a set of Win32 console commands built in.
This set of documentation describes the Windows Commands you can use to automate tasks by using scripts or scripting tools.
Prerequisites
The information that is contained in this topic applies to:
- Windows Server 2019
- Windows Server (Semi-Annual Channel)
- Windows Server 2016
- Windows Server 2012 R2
- Windows Server 2012
- Windows Server 2008 R2
- Windows Server 2008
- Windows 10
- Windows 8.1
Command shell overview
The Command shell was the first shell built into Windows to automate routine tasks, like user account management or nightly backups, with batch (.bat) files. With Windows Script Host you could run more sophisticated scripts in the Command shell. For more information, see cscript or wscript. You can perform operations more efficiently by using scripts than you can by using the user interface. Scripts accept all Commands that are available at the command line.
Windows has two command shells: The Command shell and PowerShell. Each shell is a software program that provides direct communication between you and the operating system or application, providing an environment to automate IT operations.
PowerShell was designed to extend the capabilities of the Command shell to run PowerShell commands called cmdlets. Cmdlets are similar to Windows Commands but provide a more extensible scripting language. You can run Windows Commands and PowerShell cmdlets in Powershell, but the Command shell can only run Windows Commands and not PowerShell cmdlets.
For the most robust, up-to-date Windows automation, we recommend using PowerShell instead of Windows Commands or Windows Script Host for Windows automation.
You can also download and install PowerShell Core, the open source version of PowerShell.
Incorrectly editing the registry may severely damage your system. Before making the following changes to the registry, you should back up any valued data on the computer.
To enable or disable file and directory name completion in the Command shell on a computer or user logon session, run regedit.exe and set the following reg_DWOrd value:
To set the reg_DWOrd value, use the hexadecimal value of a control character for a particular function (for example, 0 9 is Tab and 0 08 is Backspace). User-specified settings take precedence over computer settings, and command-line options take precedence over registry settings.
Command-line reference A-Z
To find information about a specific command, in the following A-Z menu, click the letter that the command starts with, and then click the command name.