ERRORLEVEL and Where.exe program

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
BoQsc
Posts: 92
Joined: 30 Jun 2014 04:10

ERRORLEVEL and Where.exe program

#1 Post by BoQsc » 08 Jan 2021 04:58

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.

T3RRY
Posts: 243
Joined: 06 May 2020 10:14

Re: ERRORLEVEL and Where.exe program

#2 Post by T3RRY » 08 Jan 2021 06:25

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
 )
 

jfl
Posts: 226
Joined: 26 Oct 2012 06:40
Location: Saint Hilaire du Touvet, France
Contact:

Re: ERRORLEVEL and Where.exe program

#3 Post by jfl » 08 Jan 2021 07:09

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.

Post Reply