How to test if an executable exists in the %PATH% from a windows batch file?

后端 未结 9 623
暖寄归人
暖寄归人 2020-12-22 20:33

I\'m looking for a simple way to test if an executable exists in the PATH environment variable from a Windows batch file.

Usage of external tools not provided by th

9条回答
  •  孤城傲影
    2020-12-22 21:08

    for %%X in (myExecutable.exe) do (set FOUND=%%~$PATH:X)
    if defined FOUND ...
    

    If you need this for different extensions, just iterate over PATHEXT:

    set FOUND=
    for %%e in (%PATHEXT%) do (
      for %%X in (myExecutable%%e) do (
        if not defined FOUND (
          set FOUND=%%~$PATH:X
        )
      )
    )
    

    Could be that where also exists already on legacy Windows versions, but I don't have access to one, so I cannot tell. On my machine the following also works:

    where myExecutable
    

    and returns with a non-zero exit code if it couldn't be found. In a batch you probably also want to redirect output to NUL, though.

    Keep in mind

    Parsing in batch (.bat) files and on the command line differs (because batch files have %0%9), so you have to double the % there. On the command line this isn't necessary, so for variables are just %X.

提交回复
热议问题