Есть ли эквивалент “which” в командной строке Windows?

Скажем, у меня есть программа X.EXE установил в папку c:\abcd\happy\ в системе. Папка находится по системному пути. Теперь предположим, что в системе есть другая программа, которая также называется X.EXE, но установлена ​​в папке c:\windows\.

Можно ли быстро узнать из командной строки, что если я наберу X.EXE какой из двух X.EXEбудут запущены? (но без необходимости поиска в каталоге или просмотра сведений о процессе в диспетчере задач).

Может быть, какая-то встроенная команда или какая-то программа, которая может делать что-то подобное? :

detect_program_path X.EXE

В *NIX-подобных системах есть очень удобная штука поиска программ с полным путем в PATH – which. 

Как это ни забавно, нечто подобное присутствует и в Windows:

В универсальных кроссплатформенных скриптах бывает весьма удобно присвоить имена с полными путями внешних утилит переменным и использовать именно их. С тем, чтобы не вбивать их хардкодом.

В юниксах это делается тривиально:

А теперь, внимание – вопрос.

Как то же самое проделать в CMD? 😉

Да, я знаю, гугл приводит в кучу намеков. Но где работоспособное решение? 😉

Мы ищем программу (в нашем случае dig) в путях PATH, если находим – то присваиваем ее одноименной переменной, которую затем и вызываем.

Скажете, нафиг так сложно?

Первое. Попробуйте получить то же самое иным путем. 😉

Второе. А если программа стоит в директории с пробелом, например, C:\Program Files (x86)? 😉

Так надо. 🙂 Это универсально и это – работает. В отличие от всех прочих частичных решений.

Если вы можете найти бесплатный компилятор Pascal, вы можете скомпилировать это. По крайней мере, это работает и показывает необходимый алгоритм.

program Whence (input, output);
  Uses Dos, my_funk;
  Const program_version = '1.00';
        program_date    = '17 March 1994';
  VAR   path_str          : string;
        command_name      : NameStr;
        command_extension : ExtStr;
        command_directory : DirStr;
        search_dir        : DirStr;
        result            : DirStr;


  procedure Check_for (file_name : string);
    { Check existence of the passed parameter. If exists, then state so   }
    { and exit.                                                           }
  begin
    if Fsearch(file_name, '') <> '' then
    begin
      WriteLn('DOS command = ', Fexpand(file_name));
      Halt(0);    { structured ? whaddayamean structured ? }
    end;
  end;

  function Get_next_dir : DirStr;
    { Returns the next directory from the path variable, truncating the   }
    { variable every time. Implicit input (but not passed as parameter)   }
    { is, therefore, path_str                                             }
    var  semic_pos : Byte;

  begin
      semic_pos := Pos(';', path_str);
      if (semic_pos = 0) then
      begin
        Get_next_dir := '';
        Exit;
      end;

      result := Copy(Path_str, 1, (semic_pos - 1));  { return result   }
      { Hmm! although *I* never reference a Root drive (my directory tree) }
      { is 1/2 way structured), some network logon software which I run    }
      { does (it adds Z:\ to the path). This means that I have to allow    }
      { path entries with & without a terminating backslash. I'll delete   }
      { anysuch here since I always add one in the main program below.     }
      if (Copy(result, (Length(result)), 1) = '\') then
         Delete(result, Length(result), 1);

      path_str := Copy(path_str,(semic_pos + 1),
                       (length(path_str) - semic_pos));
      Get_next_dir := result;
  end;  { Of function get_next_dir }

begin
  { The following is a kludge which makes the function Get_next_dir easier  }
  { to implement. By appending a semi-colon to the end of the path         }
  { Get_next_dir doesn't need to handle the special case of the last entry }
  { which normally doesn't have a semic afterwards. It may be a kludge,    }
  { but it a documented kludge (you might even call it a refinement).    }
  path_str := GetEnv('Path') + ';';

  if (paramCount = 0) then
  begin
    WriteLn('Whence: V', program_version, ' from ', program_date);
    Writeln;
    WriteLn('Usage: WHENCE command[.extension]');
    WriteLn;
    WriteLn('Whence is a ''find file''type utility witha difference');
    Writeln('There are are already more than enough of those :-)');
    Write  ('Use Whence when you''re not sure where a command which you ');
    WriteLn('want to invoke');
    WriteLn('actually resides.');
    Write  ('If you intend to invoke the command with an extension e.g ');
    Writeln('"my_cmd.exe param"');
    Write  ('then invoke Whence with the same extension e.g ');
    WriteLn('"Whence my_cmd.exe"');
    Write  ('otherwise a simple "Whence my_cmd" will suffice; Whence will ');
    Write  ('then search the current directory and each directory in the ');
    Write  ('for My_cmd.com, then My_cmd.exe and lastly for my_cmd.bat, ');
    Write  ('just as DOS does');
    Halt(0);
  end;

  Fsplit(paramStr(1), command_directory, command_name, command_extension);
  if (command_directory <> '') then
  begin
WriteLn('directory detected *', command_directory, '*');
    Halt(0);
  end;

  if (command_extension <> '') then
  begin
    path_str := Fsearch(paramstr(1), '');    { Current directory }
    if   (path_str <> '') then WriteLn('Dos command = "', Fexpand(path_str), '"')
    else
    begin
      path_str := Fsearch(paramstr(1), GetEnv('path'));
      if (path_str <> '') then WriteLn('Dos command = "', Fexpand(path_str), '"')
                          else Writeln('command not found in path.');
    end;
  end
  else
  begin
    { O.K, the way it works, DOS looks for a command firstly in the current  }
    { directory, then in each directory in the Path. If no extension is      }
    { given and several commands of the same name exist, then .COM has       }
    { priority over .EXE, has priority over .BAT                             }

    Check_for(paramstr(1) + '.com');     { won't return if file is found }
    Check_for(paramstr(1) + '.exe');
    Check_for(paramstr(1) + '.bat');

    { Not in current directory, search through path ... }

    search_dir := Get_next_dir;

    while (search_dir <> '') do
    begin
       Check_for(search_dir + '\' + paramstr(1) + '.com');
       Check_for(search_dir + '\' + paramstr(1) + '.exe');
       Check_for(search_dir + '\' + paramstr(1) + '.bat');
       search_dir := Get_next_dir;
    end;

    WriteLn('DOS command not found: ', paramstr(1));
  end;
end.

Если вы можете найти бесплатный компилятор Pascal, вы можете скомпилировать его. По крайней мере, он работает и показывает необходимый алгоритм.

program Whence (input, output);
  Uses Dos, my_funk;
  Const program_version = '1.00';
        program_date    = '17 March 1994';
  VAR   path_str          : string;
        command_name      : NameStr;
        command_extension : ExtStr;
        command_directory : DirStr;
        search_dir        : DirStr;
        result            : DirStr;


  procedure Check_for (file_name : string);
    { Check existence of the passed parameter. If exists, then state so   }
    { and exit.                                                           }
  begin
    if Fsearch(file_name, '') <> '' then
    begin
      WriteLn('DOS command = ', Fexpand(file_name));
      Halt(0);    { structured ? whaddayamean structured ? }
    end;
  end;

  function Get_next_dir : DirStr;
    { Returns the next directory from the path variable, truncating the   }
    { variable every time. Implicit input (but not passed as parameter)   }
    { is, therefore, path_str                                             }
    var  semic_pos : Byte;

  begin
      semic_pos := Pos(';', path_str);
      if (semic_pos = 0) then
      begin
        Get_next_dir := '';
        Exit;
      end;

      result := Copy(Path_str, 1, (semic_pos - 1));  { return result   }
      { Hmm! although *I* never reference a Root drive (my directory tree) }
      { is 1/2 way structured), some network logon software which I run    }
      { does (it adds Z:\ to the path). This means that I have to allow    }
      { path entries with & without a terminating backslash. I'll delete   }
      { anysuch here since I always add one in the main program below.     }
      if (Copy(result, (Length(result)), 1) = '\') then
         Delete(result, Length(result), 1);

      path_str := Copy(path_str,(semic_pos + 1),
                       (length(path_str) - semic_pos));
      Get_next_dir := result;
  end;  { Of function get_next_dir }

begin
  { The following is a kludge which makes the function Get_next_dir easier  }
  { to implement. By appending a semi-colon to the end of the path         }
  { Get_next_dir doesn't need to handle the special case of the last entry }
  { which normally doesn't have a semic afterwards. It may be a kludge,    }
  { but it's a documented kludge (you might even call it a refinement).    }
  path_str := GetEnv('Path') + ';';

  if (paramCount = 0) then
  begin
    WriteLn('Whence: V', program_version, ' from ', program_date);
    Writeln;
    WriteLn('Usage: WHENCE command[.extension]');
    WriteLn;
    WriteLn('Whence is a ''find file''type utility witha difference');
    Writeln('There are are already more than enough of those :-)');
    Write  ('Use Whence when you''re not sure where a command which you ');
    WriteLn('want to invoke');
    WriteLn('actually resides.');
    Write  ('If you intend to invoke the command with an extension e.g ');
    Writeln('"my_cmd.exe param"');
    Write  ('then invoke Whence with the same extension e.g ');
    WriteLn('"Whence my_cmd.exe"');
    Write  ('otherwise a simple "Whence my_cmd" will suffice; Whence will ');
    Write  ('then search the current directory and each directory in the ');
    Write  ('for My_cmd.com, then My_cmd.exe and lastly for my_cmd.bat, ');
    Write  ('just as DOS does');
    Halt(0);
  end;

  Fsplit(paramStr(1), command_directory, command_name, command_extension);
  if (command_directory <> '') then
  begin
WriteLn('directory detected *', command_directory, '*');
    Halt(0);
  end;

  if (command_extension <> '') then
  begin
    path_str := Fsearch(paramstr(1), '');    { Current directory }
    if   (path_str <> '') then WriteLn('Dos command = "', Fexpand(path_str), '"')
    else
    begin
      path_str := Fsearch(paramstr(1), GetEnv('path'));
      if (path_str <> '') then WriteLn('Dos command = "', Fexpand(path_str), '"')
                          else Writeln('command not found in path.');
    end;
  end
  else
  begin
    { O.K, the way it works, DOS looks for a command firstly in the current  }
    { directory, then in each directory in the Path. If no extension is      }
    { given and several commands of the same name exist, then .COM has       }
    { priority over .EXE, has priority over .BAT                             }

    Check_for(paramstr(1) + '.com');     { won't return if file is found }
    Check_for(paramstr(1) + '.exe');
    Check_for(paramstr(1) + '.bat');

    { Not in current directory, search through path ... }

    search_dir := Get_next_dir;

    while (search_dir <> '') do
    begin
       Check_for(search_dir + '\' + paramstr(1) + '.com');
       Check_for(search_dir + '\' + paramstr(1) + '.exe');
       Check_for(search_dir + '\' + paramstr(1) + '.bat');
       search_dir := Get_next_dir;
    end;

    WriteLn('DOS command not found: ', paramstr(1));
  end;
end.

кто-нибудь знает, как спросить powershell, где что-то есть?
Например, “какой блокнот” и он возвращает каталог, где Блокнот.exe запускается в соответствии с текущими путями.

ответов


самый первый псевдоним, который я сделал, когда начал настраивать свой профиль в powershell, был “который”.

New-Alias which get-command

чтобы добавить это в свой профиль, введите следующее:

"`nNew-Alias which get-command" | add-content $profile

‘ n должен гарантировать, что он начнется как новая строка.


вот фактический эквивалент *nix, т. е. он дает выход в стиле *nix.

Get-Command <your command> | Select-Object -ExpandProperty Definition

просто замените все, что вы ищете.

PS C:\> Get-Command notepad.exe | Select-Object -ExpandProperty Definition
C:\Windows\system32\notepad.exe

когда вы добавляете его в свой профиль, вы захотите использовать функцию, а не псевдоним, потому что вы не можете использовать псевдонимы с трубами:

function which($name)
{
    Get-Command $name | Select-Object -ExpandProperty Definition
}

теперь, когда вы перезагружаете свой профиль, вы можете сделать это:

PS C:\> which notepad
C:\Windows\system32\notepad.exe

Я обычно просто типа:

gcm notepad
gcm note*

GCM-псевдоним по умолчанию для Get-Command.

В моей системе, GCM Примечание * выходы:

[27] » gcm note*

CommandType     Name                                                     Definition
-----------     ----                                                     ----------
Application     notepad.exe                                              C:\WINDOWS\notepad.exe
Application     notepad.exe                                              C:\WINDOWS\system32\notepad.exe
Application     Notepad2.exe                                             C:\Utils\Notepad2.exe
Application     Notepad2.ini                                             C:\Utils\Notepad2.ini

вы получаете каталог и команду, которая соответствует то, что вы ищете.


попробуйте этот пример:

(Get-Command notepad.exe).Path

это, кажется, делает то, что вы хотите (я нашел его на http://huddledmasses.org/powershell-find-path/ )

Function Find-Path($Path, [switch]$All=$false, [Microsoft.PowerShell.Commands.TestPathType]$type="Any")
## You could  comment out the function stuff and use it as a script instead, with this line:
# param($Path, [switch]$All=$false, [Microsoft.PowerShell.Commands.TestPathType]$type="Any")
   if($(Test-Path $Path -Type $type)) {
      return $path
   } else {
      [string[]]$paths = @($pwd);
      $paths += "$pwd;$env:path".split(";")

      $paths = Join-Path $paths $(Split-Path $Path -leaf) | ? { Test-Path $_ -Type $type }
      if($paths.Length -gt 0) {
         if($All) {
            return $paths;
         } else {
            return $paths[0]
         }
      }
   }
   throw "Couldn't find a matching path of type $type"
}
Set-Alias find Find-Path

проверить это Powershell, Который

:/>  Как запустить установку Виндовс с флешки на ноутбуке ASUS?

код, предоставленный там, предполагает это

($Env:Path).Split(";") | Get-ChildItem -filter notepad.exe


мое предложение для функции Which:

PS C:\> which devcon


quickndirty матч с Unix which is

New-Alias which where.exe

но он возвращает несколько строк, если они существуют, тогда она становится


мне нравится get-command / format-list или:

gcm powershell | fl

Вы можете найти псевдонимы вроде этого:

alias -definition format-list

Tab завершение работы с gcm.


function Which([string] $cmd) {
  $path = (($Env:Path).Split(";") | Select -uniq | Where { $_.Length } | Where { Test-Path $_ } | Get-ChildItem -filter $cmd).FullName
  if ($path) { $path.ToString() }
}

# check if Chocolatey is installed
if (Which('cinst.bat')) {
  Write-Host "yes"
} else {
  Write-Host "no"
}

или эта версия, вызывающая исходную команду where.
Эта версия также работает лучше, потому что не ограничивается bat файлы

function which([string] $cmd) {
  $where = iex $(Join-Path $env:SystemRoot "System32\where.exe $cmd 2>&1")
  $first = $($where -split '[\r\n]')
  if ($first.getType().BaseType.Name -eq 'Array') {
    $first = $first[0]
  }
  if (Test-Path $first) {
    $first
  }
}

# check if Curl is installed
if (which('curl')) {
  echo 'yes'
} else {
  echo 'no'
}

у меня есть это which расширенная функция в моем профиле PowerShell:

function which {
<#
.SYNOPSIS
Identifies the source of a PowerShell command.
.DESCRIPTION
Identifies the source of a PowerShell command. External commands (Applications) are identified by the path to the executable
(which must be in the system PATH); cmdlets and functions are identified as such and the name of the module they are defined in
provided; aliases are expanded and the source of the alias definition is returned.
.INPUTS
No inputs; you cannot pipe data to this function.
.OUTPUTS
.PARAMETER Name
The name of the command to be identified.
.EXAMPLE
PS C:\Users\Smith\Documents> which Get-Command

Get-Command: Cmdlet in module Microsoft.PowerShell.Core

(Identifies type and source of command)
.EXAMPLE
PS C:\Users\Smith\Documents> which notepad

C:\WINDOWS\SYSTEM32\notepad.exe

(Indicates the full path of the executable)
#>
    param(
    [String]$name
    )

    $cmd = Get-Command $name
    $redirect = $null
    switch ($cmd.CommandType) {
        "Alias"          { "{0}: Alias for ({1})" -f $cmd.Name, (. { which cmd.Definition } ) }
        "Application"    { $cmd.Source }
        "Cmdlet"         { "{0}: {1} {2}" -f $cmd.Name, $cmd.CommandType, (. { if ($cmd.Source.Length) { "in module {0}" -f $cmd.Source} else { "from unspecified source" } } ) }
        "Function"       { "{0}: {1} {2}" -f $cmd.Name, $cmd.CommandType, (. { if ($cmd.Source.Length) { "in module {0}" -f $cmd.Source} else { "from unspecified source" } } ) }
        "Workflow"       { "{0}: {1} {2}" -f $cmd.Name, $cmd.CommandType, (. { if ($cmd.Source.Length) { "in module {0}" -f $cmd.Source} else { "from unspecified source" } } ) }
        "ExternalScript" { $cmd.Source }
        default          { $cmd }
    }
}

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.

Есть ли эквивалент "which" в командной строке Windows?

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.

Есть ли эквивалент "which" в командной строке Windows?

$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.

Есть ли эквивалент "which" в командной строке Windows?

In Windows PowerShell:

Есть ли эквивалент "which" в командной строке Windows?

Есть ли эквивалент "which" в командной строке Windows?

Есть ли эквивалент "which" в командной строке Windows?

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 .

Есть ли эквивалент "which" в командной строке Windows?

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.

Есть ли эквивалент "which" в командной строке Windows?

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.

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.

13 Answers 13

Run this in the CMD shell or batch file:

FC can also be used to compare binary files:

Есть ли эквивалент "which" в командной строке Windows?

Well, on Windows I happily run diff and many other of the GNU tools. You can do it with cygwin, but I personally prefer GnuWin32 because it is a much lighter installation experience.

So, my answer is that the Windows equivalent of diff , is none other than diff itself!

Winmerge has a command line utility that might be worth checking out.

Also, you can use the graphical part of it too depending on what you need.

Another alternative is to download and install git from here. Then, add the path to Git\bin\ to your PATH variable. This will give you not only diff, but also many other linux commands that you can use from the windows command line.

Есть ли эквивалент "which" в командной строке Windows?

FC works great by in my case it was not helpful as I wanted just the lines that are changed. And FC give additional data like file name, same lines and bilateral comparison.

but in my case I wanted only the lines that have changed and wanted those lines to be exported to different file, without any other header or data.

So I used «findstr» to compare the file :

data.txt.bak is the name of old file

data.txt is the name of new file

DiffResult.txt contains the data that is changed i.e just one line ####09

There’s also Powershell (which is part of Windows). It ain’t quick but it’s flexible, here’s the basic command. People have written various cmdlets and scripts for it if you need better formatting.

Not part of Windows, but if you are a developer with Visual Studio, it comes with WinDiff (graphical)

:/>  Что делать, если MicroSD не форматируется? 6 способов решения

But my personal favorite is BeyondCompare, which costs $30.

fc. fc is better at handling large files (> 4 GBytes) than Cygwin’s diff.

Есть ли эквивалент "which" в командной строке Windows?

DiffUtils is probably your best bet. It’s the Windows equivalent of diff.

To my knowledge there are no built-in equivalents.

The reason you getting the error with COMP is that the utility assumes the files that you are comparing are of the same size. To overcome that you can use th ‘/n’ option with which you can specify the number of lines you want to compare. (see the options supported by comp by typing ‘comp /?’ on the command line. so your command would look like :

This should solve your problem if you wanna stick to using COMP. But this will be a problem for really large files.

Though comp is an option, but I feel it is primitive and FC is a better option. you can use FORFILES and FC together to probably make a really good filecompare utility if you require one on a frequent basis.

FC is used this way for ref:

there are many options available which you can see by ‘fc /?’ hope this helps

Команды type, which, whereis, whatis и locate

Команда type

Команда type позволяет выяснить, содержится ли некоторая команда в системе, и определить тип данной команды. Команда также сообщает, является ли название команды действительным и где именно в системе находится эта команда:

Команда which

Команда which выводит полный путь до команды, если она находится в пути поиска $PATH . Команда which показывает первую найденную команду в переменной $PATH . Если надо проверить существование нескольких совпадений, используется опция -a :

Команда whereis

Команда whereis позволяет найти не только исполняемые файлы, но и файлы документации и конфигурации. Выполняет поиск в ограниченном количестве каталогов, например в каталогах стандартных двоичных файлов, каталогах библиотек и в каталогах man .

Команда whatis

Команда whatis показывает краткую информацию о команде из ее man-страницы.

Команда locate

Команда locate выполняет поиск по базе данных имен файлов, хранящейся в Linux. Для получения актуальных результатов, необходимо регулярно обновлять базу данных со списком имен файлов. Чаще всего ОС настроена таким образом, что обновление будет выполняться автоматически. Если обновление по умолчанию отключено, можно обновить базу данных вручную:

  • -q — позволяет скрыть сообщения об ошибках (например, нет доступа к файлу)
  • -n — позволяет ограничить количество возвращаемых результатов
  • -c — позволяет узнать количество файлов, соответствующих заданному критерию поиска
  • -i — позволяет провести поиск файлов без учета регистра

What is the Windows equivalent of the diff command?

I know that there is a post similar to this : here.
I tried using the comp command like it mentioned, but if I have two files, one with data like «abcd» and the other with data «abcde», it just says the files are of different sizes. I wanted to know where exactly they differ. In Unix, the simple diff tells me which row and column, the comp command in windows works if I have something like «abd» and «abc». Not otherwise. Any ideas what I can use for this?

Is there an equivalent source command in Windows CMD as in bash or tcsh?

I know that in the unix world, if you edit your .profile or .cshrc file, you can do a source

/.profile or source

/.cshrc to get the effect on your current session. If I changed something in the system variable on Windows, how can I have it effect the current command prompt session without exiting the command prompt session and opening another command prompt session?

8 Answers 8

I am afraid not, but you can start using Powershell, which does support dot sourcing. Since powershell window is really based on cmd so all your dos command will continue to work, and you gain new power, much more power.

In the usual Windows command prompt (i.e. cmd.exe), just using call mybat.bat did what I wanted. I got all the environment variables it had set.

The dos shell will support .bat files containing just assignments to variables that, when executed, will create the variables in the current environment.

env.bat This file is for setting variables. Its contents are given blow.

test.bat Our main batch file.

Now print.bat batch file to print variables. Its contents given below

Есть ли эквивалент "which" в командной строке Windows?

The only way I have found this to work is to launch a new cmd window from my own config window. eg:

The last cmd will launch a new cmd prompt with the desired settings exported to the command window.

Here’s a workaround for some limited use-cases. You can read-in a file of commands and execute them in-line. For example the calling command file looks like:

In the setup-java.bat file you can’t use % expansion. You need to use ! ; e.g.:

So you are litterally source -ing commands from a text file. You will need to test which commands sourced in this way. It took a few trials just to set some environment variables.

Администрирование windows средствами командной строки

Парадоксально, но факт: утилиты командной строки в Windows никогда не привлекали внимания ни пользователей, ни администраторов, но в тоже время состав и возможности этих утилит обогащаются каждый год. В этой статье мы поговорим о командной строке в Windows.

О том, как работать в командной строке

Наиболее часто используемой утилитой командной строки является сам командный интерпретатор — cmd.exe. Именно его мы запускаем, когда нам нужно поработать с командной строкой. Интерпретатор cmd пришел на замену command.com из мира DOS и Windows 9x. Понятно, что в окне командного интерпретатора нужно вводить команды. Команды выполняются. Если ты торопишься, и тебе не хочется ждать завершения первой команды, тогда можно ввести сразу несколько команд, разделив их амперсандом:

  • команда1 & команда2 & . & командаN

Если данную последовательность команд приходится выполнять часто, целесообразно создать командный файл — это обычный текстовый файл с расширением .cmd. Каждая команда записывается в отдельной строке, хотя это и не обязательно — можно использовать амперсанды. Иногда нужно проанализировать результат первой команды, а только потом, если результат успешен, выполнить вторую команду. Это можно реализовать с помощью двойного амперсанда:

Вторая команда будет выполнена, если код завершения первой команды равен 0 (успешное завершение). Не успел прочитать вывод программы? Тогда вывод можно передать программе more для постраничного вывода (листать вывод нужно пробелом):

В первом случае файл, если он существует, будет перезаписан, а во втором информация будет добавлена в конец файла. Для подавления вывода какой-нибудь команды можно перенаправить вывод в пустое устройство:

Для очистки «экрана» командной строки удобно использовать команду cls. Команды бывают внутренними и внешними. Внутренние команды выполняет сам cmd.exe. Внешние команды — это EXE-файлы (то есть программы) на диске. Когда мы вводим команду, cmd определяет, какая это команда. Если внутренняя, то выполняет ее сам, если команда не является внутренней, тогда cmd производит поиск исполнительного файла в текущем каталоге и по пути поиска программ (переменная окружения PATH). Просмотреть путь переменную PATH можно так:

Какие имеются команды?

Команд много и все в этой статье мы не рассмотрим. Да и вообще подробно команды рассматривать не будем. А зачем? Вводишь имя команды, пробел, слеш и вопросительный знак (параметр /?). В ответ получишь описание команды и ее параметров. Нужно просто знать, что делает та или иная команда, а уж описание прочитать проблем не составит.

    Итак, все команды можно разделить на следующие группы:

  • команды для работы с файловой системой
  • команды для управления операционной системой
  • команды мониторинга
  • сетевые команды
  • команды для поддержки Active Directory
  • команды для обслуживания жестких дисков
  • другие команды

Команды для управления операционной системой

В Unix есть очень полезная программа shutdown, с ее помощью можно не только завершить работу системы (или перезагрузить ее), но и указать время завершения работы. Аналог этой команды есть и в Windows. С ее помощью можно просто завершить работу систему, выполнить перезагрузку, завершить работу активных пользователей, перейти в режим пониженного энергопотребления и завершить сеанс без отключения компьютера. Очень полезен параметр -t, позволяющий задать в секундах таймаут операции. К командам этой группы также относится программа taskkill, которая используется для завершения работы одного или нескольких процессов. Задать процесс можно по имени образа (имени исполнимого файла — ключ /IM) или по идентификатору процесса (ключ /pid). Например:

Вообще возможностей у этой команды очень много, например, можно завершить все процессы, которые используют определенную DLL.

Команде taskkill, как было отмечено, нужно передать или имя образа или PID процесса. Узнать PID процесса можно с помощью команды tasklist. Также к данным командам относятся команды mem (вывод информации об использовании памяти), systeminfo (полная информация о системе) и tracerpt (отслеживает журнал событий и выводит отчет в формате CSV)

В Windows довольно много программ для диагностики и мониторинга сети, причем некоторые администраторы даже не подозревают о существовании этих команд.

  • arp — управление ARP-таблицей
  • ping — отправляет ICMP-пакеты на указанный узел для проверки доступности узла.
  • ping6 — версия ping для IPv6
  • tracert — трассировка маршрута к указанному узлу (показывает маршруты, то есть список маршрутизаторов, между двумя узлами сети)
  • tracert6 — версия tracert для протокола IPv6
  • pathping — усовершенствованная версия tracert
  • net — управляет сетью из командной строки
  • nskookup — позволяет просматривать записи DNS-сервера
  • netstat — вывод информации о сети
  • ipconfig — вывод информации о настройках протокола IP
  • route — вывод и изменение таблицы маршрутизации
  • netsh (routemon) — управление маршрутизатором

Особого внимания заслуживают команды net и netstat. С помощью первой команды можно произвести много различных операций. Введи команду net без параметров. В ответ получишь список команд:

Получить справку по конкретной команде можно так:

Теперь поговорим о команде netstat. Она выводит статистику использования сети и отображает информацию о текущих соединениях. Очень удобная команда. Представим, что на твоем компьютере закрыты все приложения, которые могут обращаться к сети, а обращение к сети все равно производится, о чем свидетельствуют индикаторы в system tray. Введи команду netstat -o и узнаешь, какая программа обращается к сети (параметр -o используется для вывода PID процесса).

:/>  Включение и отключение компонентов Windows 10 – инструкция

Команды обслуживания жестких дисков

Для проверки дисков используются команды chkdsk и chkntfs. Первая используется для проверки FAT-разделов, а вторая — для проверки NTFS-разделов. Для дефрагментации диска используется команда defrag. Команда recover используется для восстановления файлов с поврежденных разделов, а всем известная команда format используется для форматирования дисков.

Вместо команды fdisk, которая использовалась в Windows 9x, в современных версиях Windows используется программа diskpart. Данная программа позволяет разбить диск на разделы, создать логические диски, удалить логические диски, выбрать активный раздел и т.д. Если команда fdisk работала в интерактивном режиме, то diskpart в основном ориентирована на использование сценариев. Сценарии — это текстовые файлы, в которых содержатся инструкции, которые должна выполнить diskpart. Вызвать diskpart можно так:

Вот пример сценария diskpart:

  • select disk 0
  • clean
  • create partition primary
  • select partition 1
  • assign letter=c:
  • active
  • format
  • exit

Обрати внимание, как производится работа с объектами в diskpart. Сначала нужно выбрать какой-то объект (с помощью команды select): сначала мы выбираем диск (select disk). Затем нужно произвести операции с объектом. Мы производим две операции (clean и create partition). Потом мы уже выбираем другой объект — раздел (select partition) и производим операции с ним (делаем раздел активным и форматируем его). Можно указать размер создаваемого раздела, например:

  • create partition primary size=5000

В данном случае будет создан раздел размером в 5 Гб. К данному разделу можно отнести еще две команды — diskperf, которая управляет счетчиками производительности жесткого диска, и fsutil, которая управляет поведением файловой системы. Например, с помощью fsutil можно сбросить или установить флаг тома «грязный» (dirty), а также получить информацию о файловой системе. В общем, читай man, то есть fsutil /?

Команды для поддержки и диагностики Active Directory

В Windows для управления службой каталога используются так называемые DS-утилиты:

  • dsquery — выводит список объектов Active Directory по заданным параметрам поиска
  • dsget — возвращает атрибуты заданного объекта Active Directory, может принимать на стандартный ввод стандартный вывод команды dsquery
  • dsadd — добавляет один или несколько объектов ActiveDirectory
  • dsmod — модифицирует атрибуты существующего объекта
  • dsmove — перемещает объект из одного домена в другой
  • dsrm — удаляет один или несколько объектов

Синтаксис всех DS-команд похож, используй /? для получения справки. Для диагностики контроллера домена (DC) используется утилита DcDiag из комплекта Support Tools. Если запустить ее без параметров, то запустится 27 тестов DC (в Windows 2000 было 22 теста).

Ты помнишь, как называется команда, но когда ее вводишь, получаешь сообщение, что такая команда не найдена? Тогда попробуй использовать команду where (аналог which в Unix):

Команда where появилась в Windows 2003, в Windows 2000 и Windows 2002 (она же XP) ее нет. Для выполнения какой-то команды в строго определенное время можно использовать планировщик at. Можно задать дату запуска команды, время, интервал (например, каждый день). Программа может работать в интерактивном режиме (параметр /interactive). Если боишься редактировать файл boot.ini в блокноте, можешь использовать программу bootcfg, которая позволит тебе избежать ошибок при редактировании этого файла.

Иногда полезно опросить драйверы устройств. Для этого используется команда driverquery.

Возможности стандартного командного интерпретатора cmd в Windows довольно скудны, особенно по сравнению с командными интепретаторами Unix — ksh, bash, csh и др. В Microsoft это тоже понимают, поэтому была разработана оболочка Monad, она же MSH, которая впоследствии была переименована в Windows PowerShell. Установить MSH можно в следующих платформах: Windows XP SP2, Windows Vista, Windows Server 2003 and Windows Server «Longhorn».

Оболочка PowerShell — это интерактивный командный интерпретатор. Как и cmd, в PowerShell можно создавать сценарии, позволяющие администраторам автоматизировать управление системными задачами, как на сервере, так и на других компьютерах сети. PowerShell, в отличие от cmd, который предоставляет доступ только к файловой системе, позволяет управлять всей операционной системой и ее приложениями, например, мы можем работать с реестром Windows как с обычной файловой системой. В этой статье мы рассмотрим далеко не все возможности PowerShell.

Вот некоторые полезные команды, которые нужно знать, для начала работы в PowerShell:

  • Get-Command — получить список доступных команд
  • Get-Help — получить справку по указанной команде
  • Get-Drive — получить список дисков
  • Set-Location — изменить текущее местоположение (аналог команды cd в cmd)
  • Set-Alias — создать псевдоним для команды
  • Get-Date — вывести дату

Как и в cmd, поддерживается перенаправление ввода-вывода, например:

При запуске PowerShell автоматически запускаются следующие сценарии (если они найдены).

  • Documents and Settings\All Users\Documents\Msh\profile.msh
  • Documents and Settings\All Users\Documents\Msh\Microsoft.Management.Automation.msh_profile.msh
  • $HOME\My Documents\msh\profile.msh
  • $HOME\My Documents\msh\Microsoft.Management.Automation.msh_profile.msh

Сценарий — это обычный текстовый файл, содержащий команды PowerShell. Расширение у файла сценария должно быть msh. Синтаксис PowerShell похож на синтаксис любого другого языка высокого уровня. Рассмотрим несколько примеров:

  • MSH> 5*5
  • MSH> «Конкатенация» + «строк»
  • Конкатенация строк
  • MSH> (Get-Date).year * 5
  • 10035

Можно работать с переменными, причем поддерживаются массивы:

Перед именем переменной нужно обязательно указывать знак доллара — так PowerShell поймет, что перед ним переменная, а не значение. Нумерация элементов массива начинается с единицы. Для доступа к элементу массива используются квадратные скобки. Для добавления нового элемента в массив используется оператор +:

Кроме простых массивов поддерживаются ассоциативные массивы:

Для добавления элемента в ассоциативный массив используется вот такая конструкция:

В сценариях можно использовать условные операторы if-elseif-else, switch, а также операторы циклов while, do-while, do-until, foreach. Мы рассмотрим только оператор if-elseif-else и циклы while и foreach. Конструкция if-elseif-else следующая:

Условие задается так:

  • переменная оператор_сравнения переменная_или_значение

Цикл while выглядит так:

  • $i = 0; while($i -lt 10)
  • Данный цикл выведет числа от 0 до 9.

Теперь рассмотрим синтаксис foreach:

  • foreach (переменная in ассоциативный_массив)

Цикл foreach удобно использовать для перебора значений ассоциативного массива, например:

  • foreach ($v in Get-Process |Sort-Object Name)

Сейчас рассмотрим работу с реестром. Перейти в нужный раздел можно с помощью всем знакомой команды cd:

  • MSH> cd hkcu:SoftwareMicrosoftNotepad
  • MSH> get-property

В данном случае мы выводим настройки Блокнота. Установить значение переменной в разделе можно с помощью команды set-property (следующая команда изменит шрифт Блокнота):

  • MSH> set-property. -property lfFaceName -value «Arial»

Командную строку можно вызвать даже при установке Windows Vista — для этого во время установки нужно нажать Shift + F10

Есть ли эквивалент "which" в командной строке Windows?

Команды для работы с файловой системой:

  • type — просмотр файла
  • more — постраничный вывод файла
  • copy — копирование одного или нескольких файлов
  • move — перемещение одного или нескольких файлов (или переименование каталога)
  • del — удаление одного или нескольких файлов
  • ren — переименование файла
  • attrib — изменение атрибутов файла/каталога (скрытый, системный, только чтение, архивный)
  • fc — сравнение файлов
  • find — поиск текстовой строки в одном или нескольких файлах
  • grep — поиск текстовой строки (можно использовать регулярные выражения) в файле или в списке файлов
  • cd — смена каталога
  • dir — вывод содержимого каталога
  • tree — вывод дерева каталогов
  • md (или mkdir) — создание каталога
  • rd — удаление каталога или дерева каталогов

Votum separatum — Yuri Voinov’s Blog

Особое мнение — блог Юрия Воинова

Понедельник, 19 мая 2014 г.

Аналог which в CMD.EXE

А теперь, внимание — вопрос.

Как то же самое проделать в CMD? 😉

Да, я знаю, гугл приводит в кучу намеков. Но где работоспособное решение? 😉

Скажете, нафиг так сложно?

Первое. Попробуйте получить то же самое иным путем. 😉

Так надо. 🙂 Это универсально и это — работает. В отличие от всех прочих частичных решений.

Есть ли эквивалент "which" в командной строке Windows?

Сответствие консольных команд Windows и Linux.

При переходе с Windows на Linux и наоборот, для тех, кто знаком с командной строкой, может пригодиться небольшая справка по соответствию консольных команд этих операционных систем. Естественно, полного соответствия, за редким исключением, не бывает, и в приведенной таблице собраны команды, идентичные по результатам выполнения или функционально близкие.

Соответствие команд CMD Windows командам Linux

Если вы желаете помочь развитию проекта, можете воспользоваться кнопкой «Поделиться» для своей социальной сети

Сответствие консольных команд Windows и Linux.

При переходе с Windows на Linux и наоборот, для тех, кто знаком с командной строкой, может пригодиться небольшая справка по соответствию консольных команд этих операционных систем. Естественно, полного соответствия, за редким исключением, не бывает, и в приведенной таблице собраны команды, идентичные по результатам выполнения или функционально близкие.

Соответствие команд CMD Windows командам Linux

Если вы желаете помочь развитию проекта, можете воспользоваться кнопкой «Поделиться» для своей социальной сети

3 ответы

Использовать where команда. Первый результат в списке тот, который будет выполнен.

C:\> где блокнот C:\Windows\System32\notepad.exe C:\Windows\notepad.exe

Согласно информации это сообщение в блоге, where.exe входит в состав Windows Server 2003 и более поздних версий, поэтому он должен работать только с Vista, Win 7 и др.

В Linux эквивалентом является which команда, например which ssh.

Создан 24 фев.

Есть ли эквивалент "which" в командной строке Windows?

Введите описание изображения здесь

ответ дан 16 дек ’17, 09:12

Есть ли эквивалент "which" в командной строке Windows?

Вот небольшой скрипт cmd, который вы можете скопировать и вставить в файл с именем что-то вроде where.cmd:

@echo off
rem - search for the given file in the directories specified by the path, and display the first match
rem
rem    The main ideas for this script were taken from Raymond Chen's blog:
rem
rem         http://blogs.msdn.com/b/oldnewthing/archive/2005/01/20/357225.asp
rem
rem
rem - it'll be nice to at some point extend this so it won't stop on the first match. That'll
rem     help diagnose situations with a conflict of some sort.
rem

setlocal

rem - search the current directory as well as those in the path
set PATHLIST=.;%PATH%
set EXTLIST=%PATHEXT%

if not "%EXTLIST%" == "" goto :extlist_ok
set EXTLIST=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH
:extlist_ok

rem - first look for the file as given (not adding extensions)
for %%i in (%1) do if NOT "%%~$PATHLIST:i"=="" echo %%~$PATHLIST:i

rem - now look for the file adding extensions from the EXTLIST
for %%e in (%EXTLIST%) do @for %%i in (%1%%e) do if NOT "%%~$PATHLIST:i"=="" echo %%~$PATHLIST:i

ответ дан 23 окт ’10, 07:10

Есть ли эквивалент "which" в командной строке Windows?

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками

windows
command-line
path

or задайте свой вопрос.

Обо мне

Специалист в области Oracle RDBMS, Oracle iAS, OIM/OIF, Oracle Application Express, Oracle Designer и CASE, PL/SQL, Solaris, Sun Cluster, Web-технологий, технологий поиска, технологий кэширования, сетевых технологий, технологий хранения данных Просмотреть профиль

Оставьте комментарий