Командная строка – процессы (утилиты tasklist и taskkill) |

Find a windows process based on its description, using cmd

I get two results when I run this:

tasklist /FI “imagename eq PROCESS.exe”

Image Name                     PID Session Name        Session#    Mem Usage
========================= ======== ================ =========== ============
PROCESS.exe                   2760 Console                    1      8,156 K
PROCESS.exe                  20210 Console                    1      9,060 K

But I only want to kill ONE of them…

If I open up the Task Manager, I can see that each of my processes have different descriptions.

So all I need to do, is somehow filter by process description.

Can anyone help, please?

Thank you!

Getting process id of exe running in bat file

Extending foxidrive’s answer to show the OP’s call that requires arguments:

set "exe=las2xyz.exe"
set "arg1=[ flightpath 2 out 5 lasformat 1 target 0 FIXCLASS 1 step 20 unit *METRIC* fov 20.0 rollfix 1   sn_number *H68_038-003* lsystem *LIDAR_1* DESTSYS 144 minele -100.00 maxele 6000.00 hoff 0.00 eoff 0.00 noff 0.00 bootnr 13110201 leg 1]"
set "arg2=C:UsersDeveloper-OneDesktoplas2xyz_Data131102_003243_GPE.sdc"
set "arg3=\192.168.0.102agisMacquarie_Barwon_1310Area_01sbet_038_13110201.out"
set "arg4=131102_003243_cov"

for /f "tokens=2 delims==; " %%A in (
  'wmic process call create '"%exe%" "%arg1%" ^, "%arg2%" "%arg3%" - "%arg4%"' ^| find "ProcessId"'
) do set "PID=%%A"
echo "%PID%"

The content of the quoted arguments can contain pretty much anything except for double quote or comma. If a comma is used between arguments then it must be escaped.

There may be another syntax that allows commas within arguments, but then it would not allow parentheses within arguments.

So what to do if your command line cannot be passed through WMIC PROCESS CALL CREATE?

There is a solution. But it is not pretty 😉 I first posted this at Escaping strings when using wmic

@echo off
setlocal enableDelayedExpansion

:: Get the PID and UID for this batch process
call :getMyPID

:: Initialize an existing PIDs list
set "PIDs= "

:: Get a list of all existing child processes, except for the
:: child CMD.EXE process that was created by this FOR /F loop.
:: This is necessary because the console session that this script
:: is running in might have previously created a child process.
for /f %%A in (
  '2^>nul wmic process where "ParentProcessID=%myPID% and not CommandLine like '%%<%UID%>%%'" get ProcessID'
) do for %%B in (%%A) do set "PIDs=!PIDs!%%B "

:: Create your new process as you normally would.
:: For this demonstration, I will simply create a new CMD.EXE session 
start

:: Get the PID of the newly created child process by getting all child PIDs,
:: except for the child CMD.EXE process that was created by this FOR /F loop.
:: Ignore any PID that already exists in the %PIDs% list. The only PID left
:: is your new process.
for /f %%A in (
  '2^>nul wmic process where "ParentProcessID=%myPID% and not CommandLine like '%%<%UID%>%%'" get ProcessID'
) do for %%B in (%%A) do if "!PIDs: %%B =!" equ "!PIDs!" set "PID=%%B"

:: At this point you could append the new PID to the PIDs list using
::   set "PIDs=!PIDs!%PID% "
:: Then you can repeat the steps of creating a new proces and getting the new PID
::
:: But instead, I will simply show the result and exit
echo new PID=%PID%

exit /b


:getMyPID 
setlocal disableDelayedExpansion

:getLock

:: Establish a nearly unique temp file name using %time%
set "lock=%temp%%~nx0.%time::=.%.lock"

:: Transform the full path into a UID that can be used in a WMIC query
set "uid=%lock:=:b%"
set "uid=%uid:,=:c%"
set "uid=%uid:'=:q%"
set "uid=%uid:_=:u%"
setlocal enableDelayedExpansion
set "uid=!uid:%%=:p!"
endlocal & set "uid=%uid%"


:: Establish an exclusive lock on the temp file
:: If this fails, then loop back and try again until success
:: This guaranees no two process will ever have the same UID
2>nul ( 9>"%lock%" (

  %= The FOR /F loops creates a child CMD.EXE process which in turn invokes WMIC.         =%
  %= The child CMD.EXE process contains the WMIC query with the UID in its command line.  =%
  %= The WMIC query identifies the CMD.EXE process with the UID in the command line,      =%
  %= and returns the parent process ID, which happens to be the PID for this batch script =%
  for /f "skip=1" %%A in (
    'wmic process where "name='cmd.exe' and CommandLine like '%%<%uid%>%%'" get ParentProcessID'
  ) do for %%B in (%%A) do set "PID=%%B"
  (call ) %= Guarantee success so we don't accidently loop again =%

))||goto :getLock

:: Delete the temp file
del "%lock%" 2>nul

:: Return the result
( endlocal
  set "myPID=%PID%"
  set "UID=%uid%"
)
exit /b

Knowing the process status using procf/<pid>/status

I am working on Solaris.

:/>  Get only PID from tasklist using cmd title - Stack Overflow

I know that if there is a process running, there is a file called /proc/<PID>/status, where <PID> is the process id, and it contains a field called state.

As an example, I used my shell process:

> ps
   PID TTY         TIME CMD
 18671             0:01 tcsh

whose process id is 18671.

I had written a simple C program for extracting that information:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/procfs.h>
#include <sys/fcntl.h>

static void get_status (pid_t pid)
{
  char procpath[100];
  char buf[100];
  int pfd;
  char State[100];
  char Name[100];
  prstatus_t * pms;
  FILE *proc;


    sprintf(procpath, "/proc/%d/status", pid);

    proc = fopen(procpath,"r");
    if (proc) {
        printf("Open Successfuln");
        fgets(buf,256,proc); sscanf(buf,"Name:t%s",Name);
        fgets(buf,256,proc); sscanf(buf,"State:t%c",State);
       }
    printf("%s",Name);
    printf("%s",State);
}

int main(int argc, char **argv)
{
    get_status(18671);

}

It doesn’t produce any output:

> ./a.out
Open Successful
> 

The online material for procfs says that we can simply do a cat on proc/<pid>/status and check the state of the process.

But in my case it’s a binary file. I never saw it mentioned anywhere that it is binary.

Is there a way where I could use a simple C program to get the state of the current process?

A C solution would also be acceptable.

Командная строка процессы, утилита tasklist

Утилита командной строки tasklist служит для вывода списка процессов Windows (пример использования: “Получение списка процессов средствами командной строки и сервера Windows Script Host”)

tasklist[.exe] [/s <система>] [/u [<домен>]<пользователь> [/p <пароль>]] [/fo {TABLE|LIST|CSV}] [/nh] [/fi фильтр [/fi фильтр2 [ … ]]] [/m <модуль> | /svc | /v]

Параметры:

/s <система> – данный ключ позволяет задать имя или же IP-адрес удаленной системы. При отсутствии ключа, информация извлекается для текущей системы.

/u [<домен>]<пользователь> – позволяет задать имя домена/пользователя, под разрешением учетной записи которого должна выполниться команда. При отсутствии, принимаются права текущего пользователя, того, что запустил утилиту.

:/>  Тормозят игры на мощном пк windows 10

/p <пароль> – данный ключ актуален лишь в том случае, если прису

тствует параметр /u. Ключ задает пароль учетной записи.

/fo {TABLE|LIST|CSV} – тут мы можем задать формат выходных данных: TABLE – таблица, LIST – список и CSV – таблица в формате csv файла. При отсутствии ключа, данные выводятся в формате TABLE. Командная строка и процессы.

/nh – отключение вывода заголовка для столбца, ключ актуален лишь тогда, когда для параметр /fo установлены значения TABLE или CSV

/fi – данный ключ позволяет задать фильтры, по которым будет отсеиваться список выводимых процессов в командной строке. Фильтры можно указывать через запятую, в кавычках прописываем имя фильтра, оператор и значение.

Виды фильтров:

Оставьте комментарий

Adblock
detector