Check whether command is available in batch file

Yup:

@echo off
set found=
set program=7z.exe
for %%i in (%path%) do if exist %%i\%program% set found=%%i
echo "%found%"

Do not execute the command to check its availability (i.e., found in the PATH environment variable). Use where instead:

where 7z.exe >nul 2>nul
IF NOT ERRORLEVEL 0 (
    @echo 7z.exe not found in path.
    [do something about it]
)

The >nul and 2>nul prevent displaying the result of the where command to the user. Executing the program directly has the following issues:

  • Not immediately obvious what the program does
  • Unintended side effects (change the file system, send emails, etc.)
  • Resource intensive, slow startup, blocking I/O, ...

You can also define a routine, which can help users ensure their system meets the requirements:

rem Ensures that the system has a specific program installed on the PATH.
:check_requirement
set "MISSING_REQUIREMENT=true"
where %1 > NUL 2>&1 && set "MISSING_REQUIREMENT=false"

IF "%MISSING_REQUIREMENT%"=="true" (
  echo Download and install %2 from %3
  set "MISSING_REQUIREMENTS=true"
)

exit /b

Then use it such as:

set "MISSING_REQUIREMENTS=false"

CALL :check_requirement curl cURL https://curl.haxx.se/download.html
CALL :check_requirement svn SlikSVN https://sliksvn.com/download/
CALL :check_requirement jq-win64 jq https://stedolan.github.io/jq/download/

IF "%MISSING_REQUIREMENTS%"=="true" (
  exit /b
)

PowerShell:

On PowerShell, the Get-Command cmdlet can be considered to be the equivalent of cmd's where.exe.

Get-Command <cmd>
IF ($? -ne $true)
{
    Write-Host "<cmd> not found in path"
    # Do something about it
}