- 首先,永远不要覆盖environment variable
path,甚至不要覆盖
暂时地。改为附加您的文件夹:set "path=%path%;%myAppPath%" 或 set "path=%myAppPath%;%path%";
- 使用程序的完整路径如果你知道它,例如
"%myAppPath%\myApp"。
但是如何在未知机器上知道程序的完整路径?让我们使用where command,查看从我的cmd 窗口粘贴的示例:
==> where /F notepad.exe
"C:\Windows\System32\notepad.exe"
"C:\Windows\notepad.exe"
==> where /F pspad.exe
INFO: Could not find files for the given pattern(s).
==> where /F pspad.exe 2>NUL
==> where /R "%ProgramFiles%" /F pspad.exe 2>NUL
==> where /R "%ProgramFiles(x86)%" /F pspad.exe 2>NUL
"C:\Program Files (x86)\PSPad editor\PSPad.exe"
将我的应用程序的路径存储到一个变量中(最后一次出现):
==> set "myAppPath="
==> for /F "delims=" %G in ('where /F notepad.exe 2^>NUL') do @set "myAppPath=%~dpG"
==> set myAppPath
myAppPath=C:\Windows\
(第一次出现):
==> set "myAppPath="
==> for /F "delims=" %G in ('where /F notepad.exe 2^>NUL') do @if not defined myAppPath set "myAppPath=%~dpG"
==> set myAppPath
myAppPath=C:\Windows\System32\
将它们放在一个批处理脚本中:
@ECHO OFF
SETLOCAL EnableExtensions
set "myApp=%~1"
if not defined myApp set "myApp=java.exe"
set "myAppPath="
rem search in %path% environment variable
for /F "delims=" %%G in ('
where /F %myApp% 2^>NUL
') do set "myAppPath=%%~dpG" & goto :no1
:no1
rem search in %ProgramFiles% folder recursively
if not defined myAppPath for /F "delims=" %%G in ('
where /R "%ProgramFiles%" /F %myApp% 2^>NUL
') do if not defined myAppPath set "myAppPath=%%~dpG" & goto :no2
:no2
rem search in %ProgramFiles(x86)% folder recursively
if not defined myAppPath (
if defined ProgramFiles^(x86^) for /F "delims=" %%G in ('
where /R "%ProgramFiles(x86)%" /F %myApp% 2^>NUL
') do set "myAppPath=%%~dpG" & goto :no3
)
:no3
rem search in %SystemDrive%\ disk recursively
if not defined myAppPath for /F "delims=" %%G in ('
where /R %SystemDrive%\ /F %myApp% 2^>NUL
') do set "myAppPath=%%~dpG" & goto :no4
:no4
rem populate results
if defined myAppPath (echo could run "%myAppPath%%myapp%") else (
echo '%myapp%' not found in %SystemDrive%\ disk
)
输出:
==> 34039382.bat notepad
could run "C:\Windows\System32\notepad"
==> 34039382.bat iexplore.exe
could run "C:\Program Files\Internet Explorer\iexplore.exe"
==> 34039382.bat pspad.exe
could run "C:\Program Files (x86)\PSPad editor\pspad.exe"
==> 34039382.bat psexec.exe
could run "C:\Utils\Sysinternals\psexec.exe"
==> 34039382.bat
'java.exe' not found in C:\ disk
这篇oracle文章Deploying the JRE on Windows指出Java安装程序会将java.exe复制到系统目录中:
安装了java.exe 可执行文件的两个副本。一份在
JRE 的bin 目录。第二个副本放置在
C:\windows\system 或 C:\winnt\system32,取决于系统。
由于它位于系统目录中,因此第二个副本
java.exe 可以从任何目录位置启动无需
给出完整的路径。