How can I kill a specific cmd.exe process running on the background on the windows?

Viewed 458

I am implementing some web service written in php which executes a batch file. The batch code should be something like below,

for /f "usebackq tokens=2 delims=," %%i in (`tasklist /v /fo csv ^| findstr "cmd.exe" ^| findstr "THISFILE" ^| findstr /v "tasklist"`) do (
    set killingpid=%%i
    echo !killingpid!
    set killing=!killingpid:~1,-1!
    echo !killing!
    taskkill /f /t /pid !killing!
)
title THISFILE

rem main program starts from here.

In this batch file, I am first trying to specify the process ID which has been executed by the very same batch file, if any. Then kill it. After that name the window title to specify the process. then start the main executions.

When The PHP script is executed by using "start" command, the new cmd window will pop up, and the program will be run perfectly.

$command = "start %FILEPATH%/batch.bat"; 
$process = popen($command, 'r');

But the problem is, When I try to execute the cmd.exe on the background by using "start /b", it won't work.

$command = "start /b %FILEPATH%/batch.bat"; 
$process = popen($command, 'r');

Since other cmd.exe programs might be running, I can not write something like

taskkill /f /fi "imagename eq cmd.exe"

How can I kill the specific process without naming the window title? Somebody please give me some instruction.

1 Answers

I finally used a power-shell command. something like below.

set PIDFile=%PATH_TO%\pid.txt

rem if the same file has been running, then kill it.
if exist "%PIDFile%" (
    set /p targetPID=<%PIDFile%
    taskkill /f /t /pid !targetPID!
    del !PIDFile!
)

rem write this process ID down on the file so that other processces can read it.
powershell "Get-WmiObject win32_process -filter processid=$pid | ForEach-Object{$_.parentprocessid;}" >> %PATH_TO%\pid.txt

rem main process here

del !PIDfile!
Related