Question

I'm trying to write a batch that checks how many instances of the process "example.exe" are running, and if there are two or more instances, leave it running. But if there is only one instance running, end the process. Here's what I have:

@echo off
wmic process where name="example.exe" | find "example" /c > %temp%\variable.txt
set /p value=<%temp%\variable.txt
if %value% lss 2 goto endprocess
if %value% gtr 1 goto continue
:endprocess
start taskkill /f /im example.exe
:continue
ECHO continue
@echo off

My issue is this: It always thinks value is lss 2 (it thinks there are less than 2 instances of the process running). However, in my task manager, I can see that there is obviously 2 instances running. I think it's an issue with defining the value maybe? I don't know, I'm quite new to this. Any help? Thanks!

UPDATE

Okay I've now changed it to this (suggested by Magoo)

@echo off
wmic process where name="example.exe" | find "example" /c > "%temp%\variable.txt"
set /p value=<"%temp%\variable.txt"
if %value% equ 1 goto endprocess
if %value% neq 1 goto continue
:endprocess
start taskkill /f /im example.exe
:continue
ECHO continue
@echo off

This still doesn't exactly work, but i changed the number of instances from 1 to 0 and it ended the process. In other words, 1 process was running, but this batch file thought that 0 were running. Any ideas now?

Was it helpful?

Solution

This uses tasklist in XP Pro and higher:

@echo off
tasklist /fi "imagename eq example.exe" /nh |find /i /c "example.exe" > "%temp%\variable.txt"
set /p value=<"%temp%\variable.txt"
if %value% equ 1 taskkill /f /im example.exe
ECHO continue
@echo off

You can do it with one line and no temp file also - this uses another findstr filter to check if the number is a single 1 on a line and then && is a conditional operator that will launch taskkill if it does find 1.

@echo off
tasklist /fi "imagename eq example.exe" /nh |find /i /c "example.exe"|findstr "^1$" >nul && taskkill /f /im example.exe
ECHO continue
@echo off

OTHER TIPS

I'd suggest that you have a fault with your logic.

The code should go to endprocess if the number found is <2 - that is, 0 or 1. If the lss 2 test is failed, then the count must be 3+, so the gtr 1 test will always succeed.

I've no idea why you don't use simply

if %value% neq 1 goto continue

or even

if %value% equ 1 start taskkill /f /im example.exe

But probably you've not told us that you want to be able to detect other instance-counts - as well as concealing the name of the executable for which you are checking.

Now - it may have been really useful to show us the content of the file. Are you sure the file is actually being generated? What happens if you try using "%temp%\variable.txt" instead of %temp%\variable.txt - that is, "quote the filename" ?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top