- What is the equivalent to $? in Windows?
- 5 Answers 5
- Windows Batch Files
- Windows Powershell
- Cygwin Bash Scripting
- 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
- Есть ли эквивалент «which» в командной строке Windows?
- 22 ответов
- Equivalent to Unix eval in Windows
- 2 Answers 2
What is the equivalent to $? in Windows?
Does anybody know what is the equivalent to $? in Windows command line? Is there any?
EDIT: $? is the UNIX variable which holds the exit code of the last process
5 Answers 5
You want to check the value of %ERRORLEVEL% .
Windows Batch Files
%ERRORLEVEL% Returns the error code of the most recently used command. A non zero value usually indicates an error.
Windows Powershell
$? Contains True if last operation succeeded and False otherwise. And
$LASTEXITCODE Contains the exit code of the last Win32 executable execution.
Cygwin Bash Scripting
$? Expands to the exit status code of the most recently executed foreground program.
Sorry to dredge up an old thread, but it’s worth noting that %ERRORLEVEL% doesn’t get reset with every command. You can still test «positive» for errorlevel after several lines of subsequent—and successful—batch code.
You can reliably reset errorlevel to a clean status with ver . This example works with UnxUtils for a more Linux-ish directory listing. The reset might seem extraneous at the end, but not if I need to call this script from another.
Feel free to use this. If you haven’t seen UnxUtils, check ’em out.
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.
Есть ли эквивалент «which» в командной строке Windows?
поскольку у меня иногда возникают проблемы с путем, где один из моих собственных сценариев cmd скрыт (затенен) другой программой (ранее на пути), я хотел бы иметь возможность найти полный путь к программе в командной строке Windows, учитывая только ее имя.
есть ли эквивалент команды UNIX «which»?
в UNIX, which command печатает полный путь данной команды, чтобы легко найти и устранить эти проблемы затенения.
22 ответов
Windows Server 2003 и более поздние версии (т. е. все, что после Windows XP 32 бит) предоставляют where.exe программа, которая делает некоторые из того, что which делает, хотя он соответствует всем типам файлов, а не только исполняемые команды. (Он не соответствует встроенным командам оболочки, таким как cd .) Он даже будет принимать подстановочные знаки, так что where nt* находит все файлы в папке %PATH% и текущий каталог, чьи имена начинаются с nt .
попробовать where /? за помощью.
обратите внимание, что Windows PowerShell определяет where в качестве псевдонима для the , так что если вы хотите where.exe , вам нужно ввести полное имя вместо того, чтобы опустить
в то время как более поздние версии Windows есть where команда, вы также можете сделать это с Windows XP с помощью модификаторов переменных среды, следующим образом:
вам не нужны никакие дополнительные инструменты, и это не ограничивается PATH поскольку вы можете заменить любую переменную среды (в формате пути, конечно), которую вы хотите использовать.
и, если вы хотите, чтобы он мог обрабатывать все расширения в PATHEXT (как и сама Windows), это делает трик:
он фактически возвращает все возможности, но вы можете настроить его довольно легко для конкретных правил поиска.
В PowerShell get-command найдет исполняемые файлы в любом месте $Env:PATH .
он также находит командлеты powershell, функции, псевдонимы, файлы с пользовательскими расширениями исполняемых файлов через $Env:PATHEXT , etc определенный для текущей оболочки (довольно сродни bash type -a foo ) — что делает его лучше, чем другие инструменты, такие как where.exe , which.exe и т. д., которые не знают об этих командах PowerShell.
вы можете быстро настроить псевдоним с sal which gcm (короткая форма set-alias which get-command ).
в Windows powershell:
Если у Вас установлен PowerShell (что я рекомендую), вы можете использовать следующую команду в качестве грубого эквивалента (замените имя программы для имени исполняемого файла):
на GnuWin32 инструменты which , наряду с целым рядом других инструментов Unix.
В Windows CMD which звонки where :
удивлен, что никто не упомянул cygwin как решение пока. Если вы не возражаете использовать стороннее решение, то cygwin-это путь.
Cygwin дает вам комфорт *nix в среде Windows (и вы можете использовать его в командной оболочке Windows или использовать оболочку *nix по вашему выбору). Он дает вам целый ряд команд *nix (например, which ) для Windows, и вы можете просто включить этот каталог в ваш PATH .
в PowerShell, это gcm , который дает подробную информацию о других командах. Если вы хотите получить только путь к исполняемому файлу, используйте .Source .
например: gcm git или (gcm git).Source
- доступно для Windows XP.
- доступно с PowerShell 1.0.
- gcm — это псевдоним
золото на платформах windows, ставит все хорошие утилиты unix на стандартную Windows DOS. Использую его в течение многих лет.
Он имеет «который» включен. Обратите внимание, что он чувствителен к регистру.
NB: чтобы установить его, взорвать zip где-нибудь и добавить . \UnxUtils\usr\local\wbin\ к переменной env системного пути.
у меня есть функция в моем профиле PowerShell с именем «which»
вот как выглядит вывод:
Не знаю, поможет ли это. Опубликовано как ответ, потому что я не знаю, как форматировать код в комментарии (помогите?)
Если вы можете найти бесплатный компилятор pascal, вы можете скомпилировать это, или напишите Мне, и я могу попытаться выкопать его, или отправить обратно exe или опубликовать его где-нибудь. Я отправляю код, как бы плохо это ни было, потому что, по крайней мере, он работает и показывает необходимый алгоритм.
не в наличии Windows, но это предусмотрено сервисы для Unix и есть несколько простых пакетных скриптов, плавающих вокруг, которые выполняют то же самое, что и это этот.
лучшая версия этого, которую я нашел в Windows, — это утилита Джозефа Ньюкомера «whereis», которая доступна (с источником) из его сайт.
статью о разработке «whereis»стоит прочитать.
Я создал инструмент, похожий на NED Batchelder:
хотя мой инструмент предназначен главным образом для поиска различных версий dll, он показывает больше информации (дата, размер, версия), но не использует PATHEXT (я надеюсь скоро обновить свой инструмент).
ни один из портов Win32 Unix, которые я мог бы найти в Интернете, не является satistactory, потому что все они имеют один или несколько из этих недостатков:
- нет поддержки переменной Windows PATHEXT. (Который определяет список расширений, имплицитно добавленных к каждой команде перед сканированием пути, и в каком порядке.) (Я использую много сценариев tcl, и нет общедоступного инструмента, который мог бы их найти.)
- нет поддержки cmd.exe кодовые страницы, что делает их неправильно отображать пути с символами, отличными от ascii. (Я очень чувствителен к этому, с ç в моем первом имени : -))
- нет поддержки отдельных правил поиска в cmd.exe и командная строка PowerShell. (Ни один общедоступный инструмент не найдет .PS1 скрипты в окне PowerShell, но не в окне cmd!)
поэтому я в конце концов написал свой собственный, который правильно поддерживает все вышесказанное.
этот пакетный файл использует обработку переменных CMD для поиска команды, которая будет выполнена в пути. Примечание: текущий каталог всегда выполняется до пути) и в зависимости от того, какой вызов API используется, другие местоположения ищутся до/после пути.
Equivalent to Unix eval in Windows
Was wondering how you’d do the following in Windows:
From a c shell script (extension csh), I’m running a Python script within an ‘eval’ method so that the output from the script affects the shell environment. Looks like this:
Was wondering how I would do something like the eval statement in Windows using Windows’ built in CMD shell. I want to run a Python script within a Windows script and have the script run what the Python script prints out.
** update: specified interest in running from CMD shell.
2 Answers 2
If it’s in cmd.exe , using a temporary file is the only option [that I know of]:
(Making some guesses where details are missing from your question)
In CMD, when a batch script modifies the environment, the default behavior is that it modifies the environment of the CMD process that is executing it.
Now, if you have a batch script that calls another batch script, there are 3 ways to do it.
execute the batch file directly: Usually you don’t want this, because it won’t return to the calling batch script. This is more like goto than gosub . The CMD process just switches from one script to another.
execute with call : This is the most common way for one batch file to call another. When q.bat exits, control will return to the caller. Since this is the same CMD process, changes to the environment will still be there.
Note: If q.bat uses the EXIT statement, it can cause the CMD process to terminate, without returning control to the calling script.
Note 2: If q.bat uses EXIT /B , then the CMD process will not exit. This is useful for setting ERRORLEVEL .
Execute in a new CMD process: Since q.bat run ins a new CMD process, it affects the environment of that process, and not the CMD that the caller is running in.
Note: If q.bat uses EXIT , it won’t terminate the process of the caller.
The SETLOCAL CMD command will create a new environment for the current script. Changes in that environment won’t affect the caller. In general, SETLOCAL is a good practice, to avoid leaking environment changes by accident.
To use SETLOCAL and still push environment changes to the calling script, end the script with:
This will push the values of X and Y to the parent environment.
If on the other hand you want to run another process (not a CMD script) and have it affect the current script’s environment, than have the tool generate a batch file that makes the changes you want, then execute that batch file.