Marko
Marko

Reputation: 417

How to read and manipulate a variable from a file with a bat?

What do I want to do: 1. Run a bat file and save its PID in a txt file. 2. Run another bat that reads the previously stored PID from the txt file. 3. The second bat kills the process with the read PID from the txt.

What do I have: In the first main bat:

FOR /F %%T IN ('Wmic process where^(Name^="cmd.exe"^)get ProcessId^|more +1') DO (
SET /A ProcessId=%%T) &GOTO SkipLine                                                   
:SkipLine                                                                              
echo %ProcessId%>>ID_MAIN_BAT.txt

This works fine, i get the txt file with the PID in it.

What do I have: In the second main bat:

FOR /F "eol=; tokens=2,3* delims=, " %i in (ID_MAIN_BAT.txt) do SET /P ID=%i%
taskkill /PID %ID%

Result: The second bat doesent succed to kill the first bat with the stored PID. Can anyone help me, please?

Full second file:

I dont know, something is wrong, it doesent works. I put here my entire second page code:

@echo off
if not "%1" == "max" start /MAX cmd /c %0 max
title AutoDestroy
color cf
echo.
start "" /min winamp Countdown.mp3
DEL /F Figura1.jpg >nul
TIMEOUT /T 3
taskkill /IM winamp.exe
DEL /F Countdown.mp3 >nul
DEL /F Countdown.bat >nul
DEL /F MainBat.bat >nul
DEL /F AutoDestroy.bat >nul
for /f "delims=" %%a in (ID_MAIN_BAT.txt) do taskkill /PID %%a

Upvotes: 1

Views: 241

Answers (2)

SachaDee
SachaDee

Reputation: 9545

First BAT : Using Wmic

@echo off & cls
for /f %%a in ('Wmic process where ^(Name^="cmd.exe"^) get ProcessId ^| findstr /r [0-9]') do (
   set "$PID=%%a"
   goto:next)

:next
>ID_MAIN_BAT.txt echo %$PID%

Another and robuster way is to work with a Title in your first BAT to get the PID with Tasklist (so there is no confusion if you have another CMD open):

First BAT : Using Tasklist

@echo off
title=Test
for /f "tokens=2 delims=," %%a in ('tasklist /v /fo csv ^| findstr /i "Test"') do set "$PID=%%a"

>ID_MAIN_BAT.txt echo %$PID%

Second BAT :

for /f "delims=" %%a in (ID_MAIN_BAT.txt) do taskkill /PID %%a

Upvotes: 1

Marko
Marko

Reputation: 417

I FOUND OUT why your suggestions didnt worked out. In my main bat i have the first line: IF NOT "%1" == "max" start /MAX cmd /c %0 max & exit /B This is for oppening the bat in fullscreen mode, BUT it has a major inconvienent:

IF i delete & exit /B from the end it opens up 2 (two) of the same bat files. Doing this i realised that the PID writed in the output file belongs to the first procces that is closed by the & exit /B command, and thas why cmd couldnt kill that process, because it was already supressed by & exit /B.

IF i do not put anymore that first line (with fullscreen option) AND IF I convert the bat file into a exe i am able to use TASKKILL /IM MAIN_BAT.exe AND IT WORKS

Couldnt get it without you, guys, thank you very much!

Upvotes: 2

Related Questions