windows 如何在批处理脚本中找到应用程序的完整路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1437457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 06:44:00  来源:igfitidea点击:

How do I find full path to an application in a batch script

windowsbatch-file

提问by Nifle

How do I in a batch script find the full path to application XYZ if it is installed

如果已安装,如何在批处理脚本中找到应用程序 XYZ 的完整路径

Clarifications:

说明:

  1. The application is not in the PATH
  2. All I have is it's name in this case "ISTool.exe" and I would like to get C:\Program\ISTool\ISTool.exe
  1. 应用程序不在 PATH 中
  2. 在这种情况下,我所拥有的只是它的名称“ISTool.exe”,我想获得C:\Program\ISTool\ISTool.exe

采纳答案by Nifle

The answers I got from others worked (but slow or used extra files) and worked for any exe but didn't really suit my needs.

我从其他人那里得到的答案有效(但速度很慢或使用了额外的文件)并且适用于任何 exe,但并不真正适合我的需求。

Since I wanted to find a particular exe I went looking in the registry using REG QUERYinstead. I found a key that contained the data I wanted to find and extracted that.

因为我想找到一个特定的 exe,所以我使用REG QUERY在注册表中查找。我找到了一个包含我想要查找并提取的数据的密钥。

The result is fast, has few lines of code but is not very pretty nor reusable.

结果很快,只有几行代码,但不是很漂亮也不是可重用的。

Short example:

简短示例:

@ECHO off
SETLOCAL
set found=
FOR /F "tokens=1-3 delims= " %%a IN ('REG QUERY "HKEY_CLASSES_ROOT\Applications\ISTool.exe\shell\OpenWithISTool\command"') DO (
 set found=%%c
)

for /f "tokens=1-2" %%a in ("%found%") do (
 set my_exe=%%a
)
echo %my_exe%
ENDLOCAL

This results in "C:\Program\ISTool\ISTool.exe"(with quotes)
Note: delims= above is followed by a tab-char

这导致"C:\Program\ISTool\ISTool.exe"(带引号)
注意:上面的 delims= 后跟一个制表符

回答by paxdiablo

You can locate an executable on the path (or other path-like string if necessary):

您可以在路径(或其他类似路径的字符串,如有必要)上找到可执行文件:

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

Details can be found at the end of the help text for the "for"command, "for /?"but the summary is:

可以在"for"命令的帮助文本末尾找到详细信息,"for /?"但摘要是:

%~i    - expands %i removing any surrounding quotes.
%~fi   - expands %i to a fully qualified path name.
%~di   - expands %i to a drive letter only.
%~pi   - expands %i to a path only.
%~ni   - expands %i to a file name only.
%~xi   - expands %i to a file extension only.
%~si   - expanded path contains short names only.
%~ai   - expands %i to file attributes of file.
%~ti   - expands %i to date/time of file.
%~zi   - expands %i to size of file.
%~$P:i - searches the directories listed in the P environment variable
         and expands %i to the fully qualified name of the first one found.
         If the environment variable name is not defined or the file is not
         found by the search, then this modifier expands to the empty string.

The modifiers can be combined to get compound results:

可以组合修饰符以获得复合结果:

%~dpi    - expands %i to a drive letter and path only.
%~nxi    - expands %i to a file name and extension only.
%~fsi    - expands %i to a full path name with short names only.
%~dp$P:i - searches the directories listed in the P environment variable
           for %i and expands to the drive letter and path of the first
           one found.
%~ftzai  - expands %i to a DIR like output line.

If your executable isn't on the path (as per your edit), your best bet is to use the bare/subdirectory format of dirwhich will do it for you. From the root directory:

如果您的可执行文件不在路径上(根据您的编辑),最好的办法是使用裸/子目录格式,dir它会为您完成。从根目录:

dir /b /s ISTool.exe

will get you all of the files on that drive with that name. You then just have to parse the output. My own preference would be to use Cygwin's "find /cygdrive -name ISTool.exe"but that's because I already have it installed. You may not want that (or even have that option).

将为您提供该驱动器上具有该名称的所有文件。然后你只需要解析输出。我自己的偏好是使用 Cygwin 的,"find /cygdrive -name ISTool.exe"但那是因为我已经安装了它。你可能不想要那个(甚至有那个选项)。

Update:

更新:

That dir /b /scommand will take a while since it's basically searching the whole disk. If that's a problem you may want to consider periodically creating a cached record of all files on all disks with a cmd file like:

dir /b /s命令将需要一段时间,因为它基本上是在搜索整个磁盘。如果这是一个问题,您可能需要考虑使用 cmd 文件定期创建所有磁盘上所有文件的缓存记录,例如:

@echo off
setlocal enableextensions enabledelayedexpansion
del c:\files.cache.tmp >nul: 2>nul:
for %%d in (c d e) do (
    cd /d %%d:\
    dir /b /s >>c:\files.cache.tmp
)
del c:\files.cache >nul: 2>nul:
move c:\files.cache.tmp c:\files.cache
endlocal

You could do this with scheduled tasks either nightly (for an always-on server) or on boot (for a desktop). You could even make the script more intelligent to do it only every couple of days (I have an automated backup script that does a similar thing on the family machines I support). This creates the list in a temporary cache file then overwrites the original one to ensure the time when the file doesn't exist is minimized.

您可以在每晚(对于永远在线的服务器)或启动时(对于台式机)使用计划任务执行此操作。你甚至可以让脚本更智能,每隔几天就做一次(我有一个自动备份脚本,它在我支持的家庭机器上做类似的事情)。这会在临时缓存文件中创建列表,然后覆盖原始列表以确保最小化文件不存在的时间。

Then you can just use:

然后你可以使用:

findstr \ISTool.exe c:\files.cache

to locate all your files.

找到您的所有文件。

回答by BatchApe

Based on the really helpful answers here I hacked up these two batches which I thought I share here (I know this thread is now 3 years old, but its found as 1st match when googling ...):

基于这里真正有用的答案,我修改了这两个批次,我认为我在这里分享(我知道这个线程现在已经 3 岁了,但是在谷歌搜索时发现它是第一个匹配项......):

1) which.bat:

1)which.bat:

@echo off
REM emulate the Linux which command
if "%1" == "" (
  echo Usage: %~nx0 ^<command[.ext]^>
  exit /b
)
setlocal
for %%P in (%PATHEXT%) do (
  for %%I in (%1 %1%%P) do (
    if exist "%%~$PATH:I" (
      echo %%~$PATH:I
      exit /b
    )
  )
)

not perfect because there are allways two tests, but its fast enough so I didnt further bother about; sure its possible to 1st do a separate test with %1 only ...

不完美,因为总是有两个测试,但它足够快,所以我没有进一步担心;确保可以第一次只用 %1 做一个单独的测试......

2) findfile.bat:

2)findfile.bat:

@echo off
REM emulate the Linux find command
if "%1" == "" (
  echo Usage: %~nx0 ^<startdir^> ^<file^>
  exit /b
)
setlocal
for /f "delims=" %%A in ('dir /b /s %1\%2') do set F=%%A
if exist "%F%" echo %F%

回答by Frank Bollack

This is the closest I got. One drawback is that it works only for one drive per execution, but that could made more flexible. Another is the output, that always contains a //between the path and the filename. But per definition thats a valid path.

这是我得到的最接近的。一个缺点是它每次执行仅适用于一个驱动器,但这可以变得更加灵活。另一个是输出,它总是//在路径和文件名之间包含一个。但根据定义,这是一条有效的路径。

@ECHO OFF

SET filename=autoexec.bat

FOR /R C:\ %%a IN (\) DO (
   IF EXIST "%%a\%filename%" (

      SET fullpath=%%a%filename%
      GOTO break
   )
)
:break

ECHO %fullpath%

Will deliver: C:\\autoexec.bat

将交付: C:\\autoexec.bat

EDIT:

编辑:

For explanation, the for loop iterates through all directories starting at the given path (C:\) and check if the filename exists in that directory. If so, both variables are concatenated and stored in %fullpath% and the loop is terminated by a jump.

为便于说明,for 循环遍历从给定路径 (C:\) 开始的所有目录,并检查该目录中是否存在文件名。如果是,则将两个变量连接起来并存储在 %fullpath% 中,循环以跳转终止。

回答by bdombro

Sometimes this simple solution works, where you check to see if the output matches what you expect. The first line runs the command and grabs the last line of standard output.

有时,这个简单的解决方案会起作用,您可以在其中检查输出是否符合您的预期。第一行运行命令并获取标准输出的最后一行。

FOR /F "tokens=*" %%i in (' "xcopy /? 2> nul" ') do SET xcopyoutput=%%i
if "%xcopyoutput%"=="" echo xcopy not in path.

回答by BrainSlugs83

Alternately, programs like Everything, and UltraSearch(freeware), SwiftSearchcan search the MFT (of your NTFS partition) for files (so it can do so veryquickly), (but Wikipedia claims this kind of thing can breach your security model by finding things it's not supposed to) -- some of them look like they have some command line parameters, I've not used them, but maybe it could be helpful, if you're resorting to a full drive search.

或者,像EverythingUltraSearch(免费软件)这样的程序,SwiftSearch可以在 MFT(您的 NTFS 分区)中搜索文件(因此它可以非常快速地搜索),(但维基百科声称这种事情可以通过查找来破坏您的安全模型不应该的东西)——其中一些看起来像是有一些命令行参数,我没有使用过它们,但如果你要使用完整的驱动器搜索,它可能会有所帮助。