Page 1 of 1

ERRORLEVEL and Where.exe program

Posted: 08 Jan 2021 04:58
by BoQsc
I'd like to have a readable form of code that checks whether a program is available to be used.

It's mostly to check if the program is available from the PATH Environment Variable.


I'd like to ask if this makes any sense and is a correct way to do that, or you have any improvements on that.

Code: Select all

@ECHO OFF
WHERE cmd.exe
IF ERRORLEVEL 01 ECHO the program is not found.
PAUSE
NOTES:
/Q argument can be added to silent the output of Where.exe program.

Code: Select all

WHERE /Q cmd.exe
Also the alternative:

Code: Select all

WHERE cmd.exe >NUL 2>NUL
Update
The same above maybe can be rewritten as this:

Code: Select all

@ECHO OFF
WHERE cmd.exe || ECHO the program is not found.
PAUSE
A shorter version indeed, but maybe not much of a pleasure to read.

Re: ERRORLEVEL and Where.exe program

Posted: 08 Jan 2021 06:25
by T3RRY
My preferred solution is to define the programs name to a variable like so:

Code: Select all

 For /F "Delims=" %%G in (' where programname.ext 2^> Nul ')Do Set "%%~nG=%%G"
And then to execute you can make it conditional on the variables definition.

Code: Select all

 If defined programname (
  rem commands to execute
 )
 

Re: ERRORLEVEL and Where.exe program

Posted: 08 Jan 2021 07:09
by jfl
It's also possible to do that without invoking the where.exe program at all. Ex:

Code: Select all

C:\JFL\Temp>for %p in (notepad.exe) do @echo set N=%~$PATH:p
set N=C:\Windows\System32\notepad.exe

C:\JFL\Temp>for %p in (nothing.exe) do @echo set N=%~$PATH:p
set N=

C:\JFL\Temp>
In a batch file, it'd become:

Code: Select all

for %%p in (programname.ext) do set %%~np=%%~$PATH:p
if defined programname echo Yes it exists: %programname%
Actually there is a difference to be aware of:
where.exe will find the program _without_ having to specify the extension, whereas the for ... %~$PATH syntax requires the exact extension.
Ex: 'where notepad' finds notepad.exe, and also a script called notepad.bat if you have one in your PATH.