Reputation: 300
Is it possible to make an if statement for batch based off a user opening a program?
I tried this:
color c
echo off
cls
:props
if open WINWORD.exe (echo a & pause 10 & exit)
goto props
Doing so will simply post the error 'WINWORD was unexpected at this time.' and kill the command prompt.
What I am trying to achieve is a batch file that will:
Upvotes: 0
Views: 69
Reputation: 34919
You can search for the process using tasklist.exe
, together with find
to count the instances:
set PROC=winword.exe
tasklist /FI "IMAGENAME eq %PROC%" | find /C /I "%PROC%"
I used a variable %PROC%
to specify the process (*.exe
) name just for the sake of convenience.
find
will also exit with the return code (ErrorLevel
) of 1 if no instances have been found. With a simple if
statement you can do what you requested:
if not ErrorLevel 1 ((echo a) & timeout /T 10 /NOBREAK & exit)
I replaced the pause 10
by the timeout
command because pause
waits for the user to press any key (any arguments are ignored). The switch /NOBREAK
means to ignore any key presses.
The parenthesis around echo a
avoids a trailing space to be echoed as well.
So all together, the following should do what you asked for:
color c
echo off
set PROC=winword.exe
cls
:props
tasklist /FI "IMAGENAME eq %PROC%" | find /C /I "%PROC%" > nul
if not ErrorLevel 1 ((echo a) & timeout /T 10 /NOBREAK & exit)
timeout /T 1 /NOBREAK > nul
goto props
The (optional) > nul
portion after find
prevents it from displaying the found number of instances.
The second delay time timeout /T 1
has been inserted to avoid massive CPU load within this loop structure.
Upvotes: 2