2638

自分の cmd スクリプトの 1 つが別のプログラム (パスの前) によって隠されている (シャドウされている) というパスの問題が時々あるので、与えられた Windows コマンド ラインでプログラムへのフル パスを見つけられるようにしたいと考えています。その名前だけです。

UNIX コマンドの「which」に相当するものはありますか?

UNIX ではwhich command、特定のコマンドのフル パスを出力して、これらのシャドウイングの問題を簡単に見つけて修復します。

4

26 に答える 26

2824

Windows Server 2003以降(つまり、Windows XP 32ビット以降)は、実行可能コマンドだけでなく、すべての種類のファイルに一致しますが、where.exe一部の機能を実行するプログラムを提供します。which(のような組み込みのシェルコマンドとは一致しませんcd。)ワイルドカードも受け入れるため、名前が。で始まる現在のディレクトリwhere nt*内のすべてのファイルを検索します。%PATH%nt

where /?助けを求めてください。

Windows PowerShellはコマンドレットwhereのエイリアスとして定義されているためWhere-Object必要に応じて、拡張子where.exeを省略するのではなく、フルネームを入力する必要があります。.exeまたは、エイリアスを設定することもできます。

Set-Alias which where.exe

更新:(Get-Commandエイリアス:)を使用gcmすることをお勧めします。これは、PSにネイティブであり、すべてのコマンドタイプ(エイリアス、コマンドレット、実行可能ファイル、および関数)を取得するためです。例:

gcm notepad*
于 2008-11-20T05:52:50.717 に答える
307

それ以降のバージョンのWindowsにはwhereコマンドがありますが、次のように、環境変数修飾子を使用してWindowsXPでこれを行うこともできます。

c:\> for %i in (cmd.exe) do @echo.   %~$PATH:i
   C:\WINDOWS\system32\cmd.exe

c:\> for %i in (python.exe) do @echo.   %~$PATH:i
   C:\Python25\python.exe

追加のツールは必要ありませんPATH。使用したい環境変数(もちろんパス形式)を置き換えることができるため、これに限定されません。


そして、(Windows自体が行うように)PATHEXTのすべての拡張機能を処理できるものが必要な場合は、これでうまくいきます。

@echo off
setlocal enableextensions enabledelayedexpansion

:: Needs an argument.

if "x%1"=="x" (
    echo Usage: which ^<progName^>
    goto :end
)

:: First try the unadorned filenmame.

set fullspec=
call :find_it %1

:: Then try all adorned filenames in order.

set mypathext=!pathext!
:loop1
    :: Stop if found or out of extensions.

    if "x!mypathext!"=="x" goto :loop1end

    :: Get the next extension and try it.

    for /f "delims=;" %%j in ("!mypathext!") do set myext=%%j
    call :find_it %1!myext!

:: Remove the extension (not overly efficient but it works).

:loop2
    if not "x!myext!"=="x" (
        set myext=!myext:~1!
        set mypathext=!mypathext:~1!
        goto :loop2
    )
    if not "x!mypathext!"=="x" set mypathext=!mypathext:~1!

    goto :loop1
:loop1end

:end
endlocal
goto :eof

:: Function to find and print a file in the path.

:find_it
    for %%i in (%1) do set fullspec=%%~$PATH:i
    if not "x!fullspec!"=="x" @echo.   !fullspec!
    goto :eof

実際にはすべての可能性が返されますが、特定の検索ルールに合わせて非常に簡単に調整できます。

于 2008-11-20T05:48:16.437 に答える
208

PowerShell の下でGet-Commandは、$Env:PATH.

$ Get-Command eventvwr

CommandType   Name          Definition
-----------   ----          ----------
Application   eventvwr.exe  c:\windows\system32\eventvwr.exe
Application   eventvwr.msc  c:\windows\system32\eventvwr.msc

また、powershell ではエイリアスをwhich定義できるため、そのように定義できます。

$ sal which gcm   # short form of `Set-Alias which Get-Command`
$ which foo
...

PowerShellコマンドは単なる実行可能ファイル ( .exe.ps1など) ではありません。また、コマンドレット、関数、エイリアス、カスタム実行可能サフィックスを に設定することもできます$Env:PATHEXTGet-Commandは、これらすべてのコマンドを検索して一覧表示できます (Bash の に非常に似ていますtype -a foo)。これだけでも、通常は実行可能ファイルのみの検索に限定される 、 などwhere.exeよりも優れています。which.exe

名前の一部のみを使用して実行可能ファイルを検索する

$ gcm *disk*

CommandType     Name                             Version    Source
-----------     ----                             -------    ------
Alias           Disable-PhysicalDiskIndication   2.0.0.0    Storage
Alias           Enable-PhysicalDiskIndication    2.0.0.0    Storage
Function        Add-PhysicalDisk                 2.0.0.0    Storage
Function        Add-VirtualDiskToMaskingSet      2.0.0.0    Storage
Function        Clear-Disk                       2.0.0.0    Storage
Cmdlet          Get-PmemDisk                     1.0.0.0    PersistentMemory
Cmdlet          New-PmemDisk                     1.0.0.0    PersistentMemory
Cmdlet          Remove-PmemDisk                  1.0.0.0    PersistentMemory
Application     diskmgmt.msc                     0.0.0.0    C:\WINDOWS\system32\diskmgmt.msc
Application     diskpart.exe                     10.0.17... C:\WINDOWS\system32\diskpart.exe
Application     diskperf.exe                     10.0.17... C:\WINDOWS\system32\diskperf.exe
Application     diskraid.exe                     10.0.17... C:\WINDOWS\system32\diskraid.exe
...

カスタム実行可能ファイルの検索

実行可能ファイルが実行可能 ( +x) ビットが設定されたファイルである UNIX とは異なり、Windows 上の実行可能ファイルは、$PATHenv で指定されたディレクトリのいずれかに存在するファイルです。ファイル名サフィックスが$PATHEXTenv で指定されている変数。変数 (デフォルトは.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.CPL)。

またGet-Command、このenvを尊重します。変数で、カスタム実行可能ファイルをリストするように拡張できます。例えば

$ $Env:PATHEXT="$Env:PATHEXT;.dll;.ps1;.psm1;.py"     # temporary assignment, only for this shell's process

$ gcm user32,kernel32,*WASM*,*http*py

CommandType     Name                        Version    Source
-----------     ----                        -------    ------
ExternalScript  Invoke-WASMProfiler.ps1                C:\WINDOWS\System32\WindowsPowerShell\v1.0\Invoke-WASMProfiler.ps1
Application     http-server.py              0.0.0.0    C:\Users\ME\AppData\Local\Microsoft\WindowsApps\http-server.py
Application     kernel32.dll                10.0.17... C:\WINDOWS\system32\kernel32.dll
Application     user32.dll                  10.0.17... C:\WINDOWS\system32\user32.dll

Get-Commandその他のオプションと例については、を参照してください。

于 2014-11-26T02:07:07.443 に答える
68

Windows PowerShell の場合:

set-alias which where.exe
于 2012-11-30T23:00:43.940 に答える
44

PowerShellがインストールされている場合(これをお勧めします)、次のコマンドを大まかに同等のものとして使用できます(実行可能ファイルの名前をprogramNameに置き換えてください)。

($Env:Path).Split(";") | Get-ChildItem -filter programName*

詳細はこちら: 私のマンウイッチ!PowerShell

于 2008-11-20T05:16:34.300 に答える
37

GnuWin32ツールには、その他のwhich多数の Unix ツールと共に があります。

于 2008-11-20T06:44:18.583 に答える
30

Windows CMDwhich呼び出しの場合where:

$ where php
C:\Program Files\PHP\php.exe
于 2016-04-01T12:02:00.997 に答える
18

Cygwinはソリューションです。サードパーティのソリューションを使用してもかまわない場合は、Cygwin が最適です。

Cygwin は Windows 環境で快適な *nix を提供します (また、Windows コマンド シェルで使用することも、任意の *nix シェルを使用することもできます)。whichWindows用の* nixコマンド(のような)のホスト全体を提供し、そのディレクトリをPATH.

于 2010-10-12T17:02:50.700 に答える
13

PowerShell では、gcm他のコマンドに関する書式設定された情報を提供する です。実行可能ファイルへのパスのみを取得する場合は、 を使用します.Source

例:gcm gitまたは(gcm git).Source

ちょっとした情報:

  • Windows XP で使用できます。
  • PowerShell 1.0 以降で利用できます。
  • gcmGet-Commandコマンドレットのエイリアスです。
  • パラメーターを指定しないと、ホスト シェルによって提供される使用可能なすべてのコマンドが一覧表示されます。
  • でカスタム エイリアスを作成し、次のSet-Alias which gcmように使用できます(which git).Source
  • 公式ドキュメント: https://technet.microsoft.com/en-us/library/ee176842.aspx
于 2015-09-11T11:32:27.977 に答える
12

PowerShell プロファイルに「which」という名前の関数があります

function which {
    get-command $args[0]| format-list
}

出力は次のようになります。

PS C:\Users\fez> which python


Name            : python.exe
CommandType     : Application
Definition      : C:\Python27\python.exe
Extension       : .exe
Path            : C:\Python27\python.exe
FileVersionInfo : File:             C:\Python27\python.exe
                  InternalName:
                  OriginalFilename:
                  FileVersion:
                  FileDescription:
                  Product:
                  ProductVersion:
                  Debug:            False
                  Patched:          False
                  PreRelease:       False
                  PrivateBuild:     False
                  SpecialBuild:     False
                  Language:
于 2015-07-31T08:59:57.177 に答える
11

ここから unxutils を入手してください: http://sourceforge.net/projects/unxutils/

Windows プラットフォームでの gold は、すべての優れた UNIX ユーティリティを標準の Windows DOS に配置します。何年も使用しています。

「which」が含まれています。ただし、大文字と小文字が区別されることに注意してください。

注意: インストールするには、zip を展開して、システム パスの環境変数に ...\UnxUtils\usr\local\wbin\ を追加します。

于 2010-03-26T00:08:43.000 に答える
10

無料の 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.
于 2010-03-26T00:50:50.313 に答える
8

Windows の在庫はありませんが、Services for Unixによって提供されており、これと同じことを実現する簡単なバッチ スクリプトがいくつか出回っています。

于 2008-11-20T04:28:14.117 に答える
7

私がWindowsで見つけたこれの最高のバージョンは、Joseph Newcomerの「whereis」ユーティリティです。これは、彼のサイトから(ソースを使用して)入手できます。

「whereis」の開発に関する記事は読む価値があります。

于 2008-11-20T05:09:19.853 に答える
5

Ned Batchelder に似たツールを作成しました。

PATH 内の .dll および .exe ファイルの検索

私のツールは主にさまざまな dll バージョンを検索するためのものですが、より多くの情報 (日付、サイズ、バージョン) を表示しますが、PATHEXT は使用しません (ツールをすぐに更新したいと考えています)。

于 2008-11-20T09:39:21.383 に答える
4

Windows XP ユーザー (whereコマンドが組み込まれていない) のために、「where like」コマンドを という ruby​​gem として作成しましたwhichr

インストールするには、Ruby をインストールします。

それで

gem install whichr

次のように実行します。

C:> whichr cmd_here

于 2015-09-02T14:59:42.553 に答える
2

私はwhichかなり長い間 npm のモジュールを使用してきましたが、非常にうまく機能します: https://www.npmjs.com/package/ これは優れたマルチプラットフォームの代替手段です。

whichここで、Git に付属の に切り替えました。Git からのパスをパスに追加するだけ/usr/binで、通常はC:\Program Files\Git\usr\bin\which.exe. whichバイナリは になりますC:\Program Files\Git\usr\bin\which.exe。より高速で、期待どおりに動作します。

于 2018-06-01T02:02:25.593 に答える
0

Windows 用にコンパイルされた UNIX コマンドはすべて、which次の GitHub リポジトリからダウンロードできます: https://github.com/George-Ogden/UNIX

于 2020-07-04T17:44:52.023 に答える