Get PID from tasklist command - windows

I am using tasklist to bring me information about a specific service/proccess running on my Windows Server.
The command:
tasklist /svc /fi "SERVICES eq .Service02"
The output:
Image Name PID Services
================== ======== ============================================
app02.exe 15668 .Service02
I searched for quite a while now here on StackOverflow, other forums and also on Windows Docs but I couldn't figure out how to get the desired output, which is:
15668
I managed to do a command that kind of worked but not really...
for /f "tokens=1,2 delims= " %A in ('tasklist /svc /fi "SERVICES eq .Service02"') do echo %B
This did not give me the desired output - Instead, it gave me the following output:
C:\Users\admin>echo Name
Name
C:\Users\admin>echo ========
========
C:\Users\admin>echo 15668
15668
If I could only do something that only echoed the third line. The output would be exactly what I need. The PID.
So, I need a command that brings the name of the proccess being used by the service I provide, and return me only its PID.
Please, can someone help me?
Edit: Thanks to #Squashman I managed to do a new command:
tasklist /svc /fi "SERVICES eq .Service02" /FO csv /NH
"service02.exe","15668",".Service02"
And now the output is:
"service02.exe","15668",".Service02"
But where do I go from here?

Just use a for /F loop to capture the CSV output of the tasklist command and to extract the right token.
In Command Prompt:
#for /F "tokens=2 delims=," %P in ('tasklist /SVC /FI "Services eq .Service02" /FO CSV /NH') do #echo %~P
In a batch file:
#echo off
for /F "tokens=2 delims=," %%P in ('
tasklist /SVC /FI "Services eq .Service02" /FO CSV /NH
') do echo %%~P
The ~-modifier removes the surrounding quotation marks from the PID value.

You could of course retrieve the PID using the Service Control executable, sc.exe instead.
#For /F "Tokens=3" %%G In ('%SystemRoot%\System32\sc.exe QueryEx .Service02 ^| %SystemRoot%\System32\find.exe "PID" 2^>NUL') Do #Set "PID=%%G"
However, based upon your reply in comment, here's a quick example to show you how you may be able to perform the task without any need for retrieving the PID:
#Set "SvcName=.Service02"
#Set "SysDir=%SystemRoot%\System32"
#Rem Stop service if memory usage is greater than or equal to 150 MB
#%SysDir%\tasklist.exe /Fi "Services Eq %SvcName%" /Fi "MemUsage GE 153600" /Fo CSV /NH /Svc | %SysDir%\findstr.exe /I /R ",\"%SvcName%\"$" 1>NUL && (
%SysDir%\sc.exe Stop %SvcName%
Rem Add a delay to give the service time to stop
%SysDir%\timeout.exe /T 5 /NoBreak 1>NUL
Rem If service state is stopped then start service again
%SysDir%\sc.exe Query %SvcName% | %SysDir%\findstr.exe /R /C:"STATE *: 1 " 1>NUL && %SysDir%\sc.exe Start %SvcName%)
Line 7 can be adjusted to increase the timeout period from 5 seconds as needed.

Related

bat file loop stops too early

I am using this piece of code to run a loop within a list of active processes to identify a process by name to change the priority.
TIMEOUT /T 1
for /F "tokens=1,2" %%i in ('tasklist /FI "IMAGENAME eq java.exe" /fo table /nh') do set pid=%%j
echo %pid%
wmic process where processid=%pid% CALL setpriority 128
exit
My problem is I have more than one process called "java.exe" but I want them all to be effected by my code. How can I achieve this?
for /F "tokens=1,2" %%i in ('tasklist /FI "IMAGENAME eq java.exe" /fo table /nh') do (
echo %%j
wmic process where processid=%%j CALL setpriority 128
)
(untested)
This method will allow you to use the variable pid, but you will need to use delayed expansion.
SETLOCAL ENABLEDELAYEDEXPANSION
for /F "tokens=1,2" %%i in ('tasklist /FI "IMAGENAME eq java.exe" /fo table /nh') do set pid=%%j
echo !pid!
wmic process where processid=!pid! CALL setpriority 128
exit
The setlocal line is to allow cmd to process the variables at run-time, not phrase-time.
! denotes to process the variable at run-time, not phrase-time.

Batch File which checks for another Batch File process

so google didn't help me at all i need to ask here again.
I use this kind of method to check if my servers are running in 2 batch files.
tasklist /FI "IMAGENAME eq server_64.exe" 2> nul | find "server_64.exe" > nul
IF ERRORLEVEL == 1 (
echo Server is not running
echo.
) else (
echo Stopping Server ...
echo.
taskkill /F /IM server_64.exe > nul 2>&1
)
One to start and one to stop the servers.
Well this works great but when it comes to batch files it wont work for me...
I have one server which runs on phyton so start it via batch file.
My question is, is there a way to get somehow the batch file process status and stop it like it works for exe?
I hope i explained it good enough.
Thx in advance! :)
You can try it with a batch file like this :
#echo off
set "Process=server_64.exe"
Title Checking for status of this process ===^> "%Process%"
tasklist /nh /fi "imagename eq %Process%" 2>nul |find /i "%Process%" >nul
IF '%ERRORLEVEL%' EQU '1' (
Color 0B
echo.
echo "%Process%" is not running
) else (
Color 0C
echo.
echo Stopping "%Process%" ...
taskkill /F /IM "%Process%" > nul 2>&1
)
pause
Omg i found the solution, this was a beast...
tasklist /fi "imagename eq cmd.exe" /v /fo table /nh | find /i "Broker" 2>nul
but what is starmnge is that i cant get the output to be silnce...
when i try to mute it it gives me always error level 1.
tasklist /fi "imagename eq cmd.exe" /v /fo table /nh 2>nul | find /i "Broker" 2>nul
so whats wrong with this? ^

Build cmd command to extract PID from tasklist and use condition on the result

I'm trying to write one line cmd command that:
execute tasklist with PID filter
iterate over the output
do something if PID found
do something else if PID was not found
So I've read How to extract a specific field from output of tasklist on the windows command line and used this answer to construct this command:
for /f "tokens=2 delims=," %F in ('tasklist /nh /fi "PID eq 5284" /fo csv') do if %F NEQ "5284" (#echo no) else (#echo yes)
I didn't get the expected result. Most likely got the syntax wrong.
Just posting the answer commented by eryksun:
(for /f "tokens=2 delims=," %F in ('tasklist /nh /fo csv /fi "PID eq
5284"') do #echo yes) || #echo no

How to extract a specific field from output of tasklist on the windows command line

I ran the following command on the windows command prompt
C:>tasklist /fi "Imagename eq BitTorrent.exe"
The output of which is
Image Name PID Session Name Session # Mem Usage
================== ======== ================= =========== =========
BitTorrent.exe 6164 Console 3 24,144K
I need to extract only one field, the PID, i.e. the number 6164 from the above output.
How do I achieve this ?
More generally, how do I extract a subset(1/more) of the fields from the output of a command on the windows command line ?
Similar to previous answers, but uses specific switches in tasklist to skip header and behave correctly irrespective of spaces in image names:
for /f "tokens=2 delims=," %F in ('tasklist /nh /fi "imagename eq BitTorrent.exe" /fo csv') do #echo %~F
(as run directly from cmd line, if run from batch replace %F with %%F
the easiest way is with using WMIC:
c:\>wmic process where caption="BitTorrent.exe" get ProcessId
EDIT: As the WMIC is not part of home editions of windows:
for /f "tokens=1,2 delims= " %A in ('tasklist /fi ^"Imagename eq cmd.exe^" ^| find ^"cmd^"') do echo %B
Here is used CMD of the caption.You can change it in the find and tasklist parameters.
If this used in batch file you'll need %%B and %%A
You can use wmic command to not filter the output:
wmic process where name="BitTorrent.exe" get processid | MORE +1
UPDATE: Another way:
#Echo OFF
FOR /F "tokens=2" %%# in ('tasklist /fi "Imagename eq winamp.exe" ^| MORE +3') do (Echo %%#)
Pause&Exit
PS: Remember you need to set right the tokens if the app filename contain spaces.

How to count amount of processes with identical name currently running, using a batchfile

I would like to use a batch file to compare the number of processes named "standard.exe", that are running on my Windows 7 machine, with the number of processes named "basic.exe". If the amount of processes called "standard.exe" equals the amount of processes called "basic.exe" nothing should happen, if the numbers are unequal, basic.exe should be restarted.
Any ideas? Already found the following code to check whether a process is running, but now I would like to count the number of processes carrying the same name.
tasklist /FI "IMAGENAME eq myapp.exe" 2>NUL | find /I /N "myapp.exe">NUL
if "%ERRORLEVEL%"=="0" echo Programm is running
Thanks in advance!
Using your example simply replace the /N in find with /C to return the count of processes.
tasklist /FI "IMAGENAME eq myapp.exe" 2>NUL | find /I /C "myapp.exe"
Then you can just reduce it down to :
tasklist | find /I /C "myapp.exe"
Although as Andriy M points out it will match both myapp.exe and notmyapp.exe.
As for the second part of your question, simply do this:
set a=tasklist /FI "IMAGENAME eq myapp.exe" 2>NUL | find /I /C "myapp.exe"
set b=tasklist /FI "IMAGENAME eq myapp2.exe" 2>NUL | find /I /C "myapp2.exe"
if not a==b do (
stuff
)
If you don't want to write a file, replace the tasklist and set var1 commands with
for /f "tokens=1,*" %%a in ('tasklist ^| find /I /C "standard.exe"') do set var1=%%a
same for the second ones.
for /f "tokens=1,*" %%a in ('tasklist ^| find /I /C "basic.exe"') do set var2=%%a
There is probably a neater way to do it, but the following code seems to do the trick:
:begin
tasklist | find /I /C "standard.exe">D:\tmpfile1.txt
tasklist | find /I /C "basic.exe">D:\tmpfile2.txt
set /p var1= <D:\tmpfile1.txt
set /p var2= <D:\tmpfile2.txt
if %var1% LSS %var2% goto restart
if %var1% EQU %var2% goto wait
:wait
echo waiting..
ping -n 300 127.0.0.1 > nul
goto begin
:restart
echo error has occured, all processes will be restarted
taskkill /f /im standard.exe
taskkill /f /im basic.exe
ping -n 30 127.0.0.1 > nul
goto begin
Cheers!

Resources