正确的技术,以从CMD.EXEfind32位和64位版本的Vista / Windows 7中的应用程序

背景

我有一个现有的CMD脚本工作正常。 它像这样从程序文件启动一个应用程序

"%PROGRAMFILES%\MyApp\app.exe" 

问题

  • 它在32位版本的Windows(Vista,Windows 7)上正常工作,
  • 但在64位版本的Windows上,应用程序将被安装到“Program Files(x86)”中,而不是“Program Files”(这是32位操作系统上发生的情况)

我在寻找什么

  • 一个强大的处理这两种情况的脚本(即它“做正确的事情”取决于它所在的操作系统)
  • 一种只使用CMD.EXE中的特性的方法。 我好奇使用Powershell等的解决scheme,但那些帮助不了我–PowerShell不会在这个脚本运行的机器上。

类似于马特的正确答案 。 基本上在这个版本中,完整的path被validation。

 SET AppExePath="%ProgramFiles(x86)%\MyApp\app.exe" IF NOT EXIST %AppExePath% SET AppExePath="%ProgramFiles%\MyApp\app.exe" %AppExePath% 

这是我能想到的最好的:

 set strProgramFiles=%ProgramFiles% if exist "%ProgramFiles(x86)%" set strProgramFiles=%ProgramFiles(x86)% "%strProgramFiles%\MyApp\app.exe" 

基本上,您需要testingProgramFiles(x86)环境variables以确定您是否在64位Windows中。 这里是一个示例batch file。

 if "%programfiles(x86)%zzz"=="zzz" goto 32BIT echo 64-bit Windows installed "%PROGRAMFILES(x86)%\MyApp\app.exe" goto END :32BIT echo 32-bit Windows installed "%PROGRAMFILES%\MyApp\app.exe" :END 

另一种方法是在32位cmd.exe下运行脚本,以便它可以利用WOW64文件系统redirect和环境variables修改 。 如果你可以修改调用者,你甚至不需要修改有问题的脚本。

您甚至可以在64位cmd.exe下执行脚本时检测脚本,并使用32位cmd.exe重新启动它自己:

 @echo off if "%PROCESSOR_ARCHITECTURE%" == "x86" goto :x86 echo Restarting using Wow64 filesystem redirection: %0 %* %SystemRoot%\SysWOW64\cmd.exe /c %0 %* exit /b %ERRORLEVEL% :x86 rem Rest of script follows... 

请注意,得到这个黑客错误可能会导致产生无尽的cmd.exe进程。 这就是为什么我使用goto和标签而不是if ... ( ... ) :命令行参数可能包含括号, if ... ( ... )执行第一个右括号的贪婪search。