Search code examples
windowsbatch-filecommand

Check whether command is available in batch file


I'm writing a batch file for Windows and use the command 7z (7-Zip). I have put the location of it in the PATH. Is there a relatively easy way to check whether the command is available?


Solution

  • An attempt to execute 7z.exe will return an %errorlevel% of 9009 if the command is not found. You can check that.

    7z.exe
    if %errorlevel%==9009 echo Command Not Found
    

    Note: This solution is viable for this specific 7zip use case, and likely for plenty of others. But as a general rule, executing a command to determine whether it's present could potentially be harmful. So make sure you understand the effect of executing the command you're checking for, and use your discretion with this approach.