I have the following batch file, which uses ADB to monitor device logs and searches for a string:
@ECHO OFF
ECHO Starting log monitor...
START /B adb.exe logcat > log
:LOOP
(TYPE log | FIND "string to find") > NUL
IF "%errorlevel%" == "1" GOTO LOOP
:END
ECHO String found!The script starts the logcat command, which runs asynchronously and in the background, using START /B.
After the string is found, I would like to end the asynchronous logcat command, as it is no longer needed.
Is there any way of the main script telling the asynchronous script to end?
I know that I could technically use adb.exe kill-server or taskkill /F /IM adb.exe to end all ADB processes, but I need to only end the logcat command and continue running all other instances of ADB.
1 Answer
@echo off
echo/ starting log monitor...
start /b adb.exe logcat >.\mylogcat.log
:loop
find "string to find" .\mylogcat.log >nul || ( >nul timeout 15 /nobreak & goto loop )
echo/ string found!
wmic process where "name like '%%adb.exe%%' and commandline like '%%logcat%%'" deleteYou can kill your process using the combination of the process name and part of the command line used to start it with wmic:
wmic process where "name like '%%adb.exe%%' and commandline like '%%logcat%%'" deleteYou can use the operator || to keep your loop, and also add a timeout to that monitoring loop...
:loop
find "string to find" .\mylogcat.log >nul || ( >nul timeout 15 /nobreak & goto loop ) Some further reading:
[√] Find
[√] Timeout
[√] Goto :Label
[√] Conditional Execution || && ...
[√] Difference between “delete” and “call terminate” for WMIC
[√] Understanding start, 2>nul, cmd, and other symbols in a batch file
In PowerShell using Get-WmiObject:
Get-WmiObject Win32_Process | % { if ($_.ProcessName -like '*adb.exe*' -and $_.CommandLine -like '*mylogcat.log*') {kill $_.ProcessId}} Using Get-CimInstance Win32_Process:
Get-CimInstance Win32_Process -Filter "name='adb.exe'" | % { if ($_.CommandLine -like '*mylogcat.log*') {kill $_.ProcessId}}
# Or....
Get-CimInstance Win32_Process -Filter "name='adb.exe'" |
% { if ($_.CommandLine -like '*mylogcat.log*') {kill $_.ProcessId}}Additional resources: