BATCH - IF使用变量进行文件路径的语句

时间:2012-03-20 09:36:58

标签: batch-file cmd

我有一个批处理脚本,我认为我的问题与括号有关,但我不知道如何解决它

这就是它

REM  Detect if the OS is x86 or x64
IF DEFINED PROGRAMFILES(x86) (
  REM x64
  SET "_PROGRAMFILES=%PROGRAMFILES(x86)%"
  GOTO MAIN_PROGRAM
) ELSE (
  REM x86
  SET "_PROGRAMFILES=%PROGRAMFILES%"
  GOTO MAIN_PROGRAM
)
:MAIN_PROGRAM
SET "MY_EXE=%_PROGRAMFILES%\MYFOLDER\MYEXE.exe"
IF EXIST "%MY_EXE%" (
    ECHO YES
) ELSE (
    ECHO NO
)

在x86上运行此命令,确定路径是C:\ Program Files \ MYFOLDER \ MYEXE.exe

在x64上运行它并且它“炸弹”“此时未预期”

我很确定它与路径C:\ Program Files(x86)\

有关

我如何解决(x86)就是问题


NEW

    REM Is the OS x86

    IF "%PROCESSOR_ARCHITECTURE%" == "x86" (

      SET "_PROGRAMFILES=%PROGRAMFILES%"
      SET "_ARCH=x86"  

      ECHO CPU Architecture is: "%_ARCH%"
      ECHO Program Files Directory is: "%_PROGRAMFILES%"

      GOTO MAIN_PROGRAM

    ) 

    REM Is the OS AMD64

    IF "%PROCESSOR_ARCHITECTURE%" == "AMD64" (

      SET "_PROGRAMFILES=%PROGRAMFILES(x86)%"
      SET "_ARCH=x86"

      ECHO CPU Architecture is: "%_ARCH%"
      ECHO Program Files Directory is: "%_PROGRAMFILES%"

      GOTO MAIN_PROGRAM

    )


    GOTO ERROR_OS_ARCH

    :ERROR_OS_ARCH

    CLS

    cWnd.exe /SHOW @

    ECHO.
    ECHO Error 100: Operating System Architecture not Supported. Contact your IT Department
    ECHO.

    EXIT /B

2 个答案:

答案 0 :(得分:1)

我在使用else运算符时遇到了一些问题......你可以用两个if语句来完成它。

IF DEFINED PROGRAMFILES(x86) (
  REM x64
  SET "_PROGRAMFILES=%PROGRAMFILES(x86)%"
  GOTO MAIN_PROGRAM
)
IF NOT DEFINED PROGRAMFILES(x86) (
  REM x86
  SET "_PROGRAMFILES=%PROGRAMFILES%"
  GOTO MAIN_PROGRAM
)

或者也可能是你在变量名中使用():PROGRAMFILES(x86)和批处理混淆了。也许可以尝试将该变量名称更改为 PROGRAMFILES_x86 。只是在这里吐痰。

答案 1 :(得分:1)

我觉得这很简单......

如何检测操作系统:

FOR /F "tokens=1 skip=1" %%a IN ( 'wmic os get OSArchitecture' ) DO (IF /I '%%a'== '64-bit' (set osArch=64) ELSE (IF /I '%%a'== '32-bit' (set osArch=32)))

接下来转到正确的Program Files文件夹:

FOR /F "tokens=1,2 delims==" %%a IN ( '^set "ProgramFiles"' ) DO set _PROGRAMFILES=%%a

实际上你只需要上述行。

试试这个......

FOR /F "tokens=1,2 delims==" %%a IN ( 
'^set "ProgramFiles"' 
) DO set _PROGRAMFILES=%%a
GOTO MAIN_PROGRAM

:MAIN_PROGRAM
SET "MY_EXE=%_PROGRAMFILES%\MYFOLDER\MYEXE.exe"
IF EXIST "%MY_EXE%" (
    ECHO YES
) ELSE (
    ECHO NO
)