Windows get process info by pid

Suppose I know the process ID. I want to find the process name by its ID, using windows batch script. How can I do this?

The basic one, ask tasklist to filter its output and only show the indicated process id information

tasklist /fi "pid eq 4444" 

To only get the process name, the line must be splitted

for /f "delims=," %%a in ('
    tasklist /fi "pid eq 4444" /nh /fo:csv
') do echo %%~a

In this case, the list of processes is retrieved without headers (/nh) in csv format (/fo:csv). The commas are used as token delimiters and the first token in the line is the image name

note: In some windows versions (one of them, my case, is the spanish windows xp version), the pid filter in the tasklist does not work. In this case, the filter over the list of processes must be done out of the command

for /f "delims=," %%a in ('
    tasklist /fo:csv /nh ^| findstr /b /r /c:"[^,]*,"4444","
') do echo %%~a

This will generate the task list and filter it searching for the process id in the second column of the csv output.

edited: alternatively, you can suppose what has been made by the team that translated the OS to spanish. I don’t know what can happen in other locales.

tasklist /fi "idp eq 4444" 

You can find Process Name from Process ID (PID) using the command tasklist in command line windows, apart from command prompt, you can even get process name for the associated Process ID (PID) using either Task Manager or Resource Monitor.

You can get Process Name from Process ID (PID) using the command tasklist in command prompt. TaskList command displays all running applications and associated services with their Process ID (PID).

The following command displays the associated Process Name for the Process ID 488.

tasklist /svc /FI "PID eq 488"

Get Process Name from PID using Command Prompt in Windows



Get Process Name by Process ID (PID) from Remote Computer:

Use below command If you want to get Process Name from Process ID (PID) from Remote Computer.

tasklist /s "remote-pc" /svc /FI "PID eq 488"

Find Process Name from PID through Task Manager

1. Open the Task Manger, click the menu View and click Select Columns.

Get Process Name from PID using Task Manger

2. Select the column Process Identifier(PID) and click OK.

Get Process Name from PID using Task Manger

3. Now you can find Process Name (Image Name) by mapping PID value.

Get Process Name from PID using Task Manger

Is there a command equivalent to ‘ps’ on Unix that can list all processes on a Windows machine?

asked Sep 10, 2008 at 5:50

readonly's user avatar

1

Working with cmd.exe:

tasklist

If you have Powershell:

get-process

Via WMI:

wmic process

(you can query remote machines as well with /node:ComputerOrIP, and there are a LOT more ways to customize this command: link)

aggserp4's user avatar

answered Sep 10, 2008 at 5:52

Factor Mystic's user avatar

Factor MysticFactor Mystic

12.4k7 gold badges46 silver badges53 bronze badges

6

I wanted to mention that WMIC (pam’s entry) can do a lot more. Have a look at my WMIC snippets page, which is a cheatsheet showing many of the common ways to use WMIC (with sample output shown) here

answered Sep 15, 2008 at 9:53

user4197's user avatar

user4197user4197

5674 silver badges10 bronze badges

2

  1. Tasklist

  2. WMIC /OUTPUT:C:ProcessList.txt PROCESS get Caption,Commandline,Processid

or

 WMIC /OUTPUT:C:ProcessList.txt path win32_process get Caption,Processid,Commandline

answered Feb 15, 2010 at 8:06

I tried on Windows 7. The command is: TASKLIST /FI "IMAGENAME eq application_name"

Eg: c:>TASKLIST /FI "IMAGENAME eq notepad.exe"

To show all process with port details:

c:> TASKLIST

Also to kill the process you can use c:> pskill or tskill processname

Eg: c:> tskill notepad

answered Nov 8, 2011 at 11:56

3

tasklist or pslist from sysinternals. Also, get-process is amazing from PowerShell.

answered Sep 10, 2008 at 5:57

Hafthor's user avatar

HafthorHafthor

9801 gold badge13 silver badges23 bronze badges

If you use Powershell, it has the ‘ps’ command (it is aliased to Get-Process)

answered Sep 10, 2008 at 7:48

user15123's user avatar

1

To kill a process use:

TASKKILL /F /IM processname.exe

For example:

TASKKILL /F /IM firefox.exe

Gaff's user avatar

Gaff

18.3k15 gold badges56 silver badges68 bronze badges

answered May 8, 2013 at 11:58

1

If you running windows XP try using the ‘tasklist’ command. I tried it out with Vista and it seems to also work.

answered Sep 10, 2008 at 5:52

Marcel's user avatar

MarcelMarcel

3711 gold badge2 silver badges5 bronze badges

open windows command prompt

C:>tasklist                       // list all the tasks


C:>Taskkill /IM firefox.exe /F     // Kill task by name

or

C:>Taskkill /PID 26356 /F           // kill task by PId

answered Jun 1, 2018 at 4:58

spacedev's user avatar

Use this command to see all the processes in windows machine

tasklist /svc

answered Sep 5, 2014 at 7:30

LOKESH's user avatar

LOKESHLOKESH

1311 silver badge6 bronze badges

4

I had following problem on Windows 2003 SP2: Tasklist didn’t return any output on stdout or stderr, when called from a process started as Windows service (even under Local Account). Tasklist returned with the (undocumented) code 128.

Called from the same program started as a normal process (not as service), it did run.

No help to change it. I couldn’t find any reason or solution but use «pslist /accepteula» of sysinternal instead of it.

Same problem with taskkill: I had to replace it whith pskill.

answered May 16, 2012 at 6:58

Olivier Faucheux's user avatar

I have done a msproject ( c source code) , archive is available at :
lsproc.zip project archive

and exe file:
lsproc.exe binary

this is a command line tool
output:

lsproc 
Thierry Bremard
t.bremard@gmail.com
list binary files and driver with their local path on disks
most of code retreived from msdn site
--------------------

Process ID: 0
--------------------

Process ID: 4
<unknown>  (PID: 4)
<unknown>
    PageFaultCount             : 0x00002E4B
    PeakWorkingSetSize         : 0x00419000
    WorkingSetSize (Mem usage) : 0x0003A000 (232 ko)
    QuotaPeakPagedPoolUsage    : 0x00000000
    QuotaPagedPoolUsage        : 0x00000000
    QuotaPeakNonPagedPoolUsage : 0x00000000
    QuotaNonPagedPoolUsage     : 0x00000000
    PagefileUsage              : 0x00000000
    PeakPagefileUsage          : 0x00000000
--------------------

Process ID: 764
smss.exe  (PID: 764)
SystemRootSystem32smss.exe
    PageFaultCount             : 0x000000D6
    PeakWorkingSetSize         : 0x00082000
    WorkingSetSize (Mem usage) : 0x0006C000 (432 ko)
    QuotaPeakPagedPoolUsage    : 0x00006C34
    QuotaPagedPoolUsage        : 0x00001854
    QuotaPeakNonPagedPoolUsage : 0x000004D8
    QuotaNonPagedPoolUsage     : 0x00000280
    PagefileUsage              : 0x0002C000
    PeakPagefileUsage          : 0x00030000
--------------------

Process ID: 816
--------------------

Process ID: 844
winlogon.exe  (PID: 844)
??C:WINDOWSsystem32winlogon.exe
    PageFaultCount             : 0x0000261D
    PeakWorkingSetSize         : 0x00B58000
    WorkingSetSize (Mem usage) : 0x0029B000 (2668 ko)
    QuotaPeakPagedPoolUsage    : 0x0001B054
    QuotaPagedPoolUsage        : 0x000185A4
    QuotaPeakNonPagedPoolUsage : 0x0000C988
    QuotaNonPagedPoolUsage     : 0x0000B6A0
    PagefileUsage              : 0x005EC000
    PeakPagefileUsage          : 0x006C6000
--------------------

...
    PeakPagefileUsage          : 0x03277000
--------------------

Process ID: 2712
lsproc.exe  (PID: 2712)
C:Documents and SettingsLoginXBureaulsproc.exe
    PageFaultCount             : 0x000000EC
    PeakWorkingSetSize         : 0x000F1000
    WorkingSetSize (Mem usage) : 0x000E4000 (912 ko)
    QuotaPeakPagedPoolUsage    : 0x000032B4
    QuotaPagedPoolUsage        : 0x000032B4
    QuotaPeakNonPagedPoolUsage : 0x00000400
    QuotaNonPagedPoolUsage     : 0x00000398
    PagefileUsage              : 0x00042000
    PeakPagefileUsage          : 0x0005C000
There are 131 drivers:
--------------------
   1: ntkrnlpa.exe
WINDOWSsystem32ntkrnlpa.exe
--------------------
   2: hal.dll
WINDOWSsystem32hal.dll
--------------------
   3: KDCOM.DLL
WINDOWSsystem32KDCOM.DLL
--------------------
   4: BOOTVID.dll
WINDOWSsystem32BOOTVID.dll


...


--------------------
 129: HTTP.sys
SystemRootSystem32DriversHTTP.sys
--------------------
 130: hiber_WMILIB.SYS
SystemRootSystem32Drivershiber_WMILIB.SYS
--------------------
 131: ntdll.dll
WINDOWSsystem32ntdll.dll



--------------

answered Mar 25, 2011 at 18:47

Thierry BremardThierry Bremard

1

Using WMI and Powershell you can do:

Get-WMIObject -Class Win32_Process

Then you can filter properties using Select-Object and show in GUI using Out-GridView.

answered Sep 16, 2020 at 7:29

Wasif's user avatar

WasifWasif

7,5932 gold badges15 silver badges32 bronze badges

For more process info

running in cmd,handle is the process id:

wmic.exe path Win32_Process where handle='22792' get Commandline /format:list

result:

/path/to/app.exe [args specified goes here]

answered Jun 17, 2021 at 2:38

sammy's user avatar

sammysammy

1012 bronze badges

Hello if you want to list running process ID’s on a Windows machine then open a cmd screen and type:

netstat -aon | more

use the Enter key to scroll.

answered Aug 14, 2014 at 14:05

1

On a database, I can get a list of all the currently running processes, and the sql command that kicked them off.

I’d like to do a similar thing on a windows box.

I can get the list of processes, but not the command line that kicked them off.

My question is: Given a PID on Windows — how do I find the command line instruction that executed it?

Assumptions:

  • Windows 7 and equivalent servers

asked Jun 3, 2015 at 22:55

Hawkeye's user avatar

Powershell and WMI.

Get-WmiObject Win32_Process | Select ProcessId,CommandLine

Or

Get-WmiObject -Query "SELECT CommandLine FROM Win32_Process WHERE ProcessID = 3352"

Note that you have to have permissions to access this information about a process. So you might have to run the command as admin if the process you want to know about is running in a privileged context.

answered Jun 3, 2015 at 23:20

Ryan Ries's user avatar

Ryan RiesRyan Ries

55.2k10 gold badges140 silver badges199 bronze badges

8

You can use the WMI subsystem, using WMIC.EXE to get to this information. Assuming a PID of 600:

wmic.exe path Win32_Process where handle='600' get name, commandline  /format:list

You can also search for name, or other characteristic of the process. Use this command to list all attributes:

wmic.exe path Win32_Process get  /format:list

answered Jun 3, 2015 at 23:39

RobW's user avatar

RobWRobW

2,7661 gold badge17 silver badges22 bronze badges

1

The other answers are certainly good options that will serve you well in an automated system because of their command line nature (and I see from the tag that that’s what you wanted). Of course, some folks might want to explore this kind of info with a GUI, so here’s an alternative along those lines.

Process Explorer is a Sysinternals tool maintained by Microsoft. It can display the command line of the process in the process’s properties dialog as well as the parent that launched it, though the name of that process may no longer be available. Here’s the process properties dialog:

process properties dialog

If you want a more detailed audit trail of when a process was launched and under what conditions, you can turn to another Sysinternals tool called Process Monitor. Here you can filter for «Process started» events, learn about the environment the process was launched in, and see what other events were occurring around that time. It’s quite a powerful program. Here’s the event properties dialog:

event properties dialog

BE77Y's user avatar

BE77Y

2,5973 gold badges18 silver badges23 bronze badges

answered Jun 4, 2015 at 7:26

Corrodias's user avatar

CorrodiasCorrodias

2611 silver badge3 bronze badges

6

To complement Ryan Ries’ helpful PowerShell answer with a shorter alternative via the -Filter parameter that also uses Get-CimInstance instead of the deprecated-since-v3 Get-WmiObject cmdlet.

# Target a process by its PID (process ID) and report its command line, 
# using the PowerShell session's own PID as an example ($PID).
(Get-CimInstance Win32_Process -Filter "ProcessId=$PID").CommandLine

# Alternatively, target process(es) by name (may return multiple processes), 
# using Notepad.exe as an example.
# Select-Object is used to report both the PID and the command line.
Get-CimInstance Win32_Process -Filter "Name='Notepad.exe'" |
  Select-Object ProcessId, CommandLine

The -Filter parameter essentially allows you to pass the WHERE clause of a WQL statement instead of passing a full query statement via -Query.

answered Dec 18, 2018 at 23:26

mklement's user avatar

mklementmklement

5365 silver badges11 bronze badges

Содержание

  1. Как получить подробные сведения о процессах в Windows 7
  2. Как узнать PID (идентификатор процесса) в Windows
  3. Как узнать PID (идентификатор процесса) в диспетчере задач
  4. Как узнать PID (идентификатор процесса) в командной строке
  5. Finding the process ID
  6. Task Manager
  7. The tasklist command
  8. TList utility
  9. The .tlist debugger command
  10. PowerShell Get-Process command
  11. CSRSS and user-mode drivers
  12. Как узнать какой порт использует программа
  13. Определения порта программы стандартными средствами Windows
  14. Поиск идентификатора процесса PID
  15. Поиск порта процесса
  16. Программы для просмотра сетевых соединений
  17. TCPView
  18. CurrPorts
  19. Поиск и сравнение процесса
  20. Решение

Как получить подробные сведения о процессах в Windows 7

В статье «Анализ использования памяти с помощью Монитора ресурсов Windows 7» я рассказывал, как использовать Монитор ресурсов (Resource Monitor) для анализа распределения памяти в Windows 7. При этом я упомянул, что графа «Образ» (Image) в таблице «Процессы» (Processes) на вкладке «Память» (Memory) позволяет идентифицировать процессы приложений по имени исполняемого файла. Например, процесс «notepad.exe» со всей очевидностью принадлежит Блокноту (Notepad).

Однако далеко не все процессы можно так легко опознать, и я получил уже немало вопросов от читателей по этому поводу. С идентификацией менее очевидных процессов поможет Диспетчер задач (Task Manager), и в этой статье я расскажу, как его использовать.

Запуск Диспетчера задач

Запустить Диспетчер задач в Windows 7 можно несколькими способами. Во-первых, можно нажать на панели задач правой кнопкой мыши и выбрать опцию «Запустить диспетчер задач» (Start Task Manager). Во-вторых, можно воспользоваться клавишной комбинацией [Ctrl]+[Shift]+[Esc]. И наконец в-третьих, можно запустить исполняемый файл Диспетчера задач из строки поиска меню «Пуск» (Start) — для этого введите taskmgr и нажмите [Enter]. В открывшемся окне выберите вкладку «Процессы» (Processes).

На вкладке «Процессы» есть графа «Описание» (Description, рис. A), в которой приводятся подробные сведения о каждом процессе.

Добавление столбцов на вкладке «Процессы»

Чтобы получить более подробные сведения о процессах Windows 7, воспользуйтесь командой «Выбрать столбцы» (Select Columns) в меню «Вид» (View). Появится диалоговое окно «Выбор столбцов страницы процессов» (Select Process Page Columns), показанное на рис. B. Отсюда можно добавить на вкладку «Процессы» дополнительные колонки — например, столбец «Путь к образу» (Image Path Name), в котором указывается полный путь к файлу, инициировавшему запущенный процесс Windows 7, или графу «Командная строка» (Command Line), где приводится полная команда для запуска процесса со всеми параметрами и переключателями.

Помимо этих столбцов, на вкладку «Процессы» можно добавить и многие другие. Всего в окне «Выбор столбцов страницы процессов» доступно более 30 опций, описание которых не входит в задачи данной статьи. Узнать о назначении всех колонок можно из справочной статьи «Что означают столбцы памяти Диспетчера задач?» на сайте Microsoft.

Опция «Открыть место хранения файла»

Помимо добавления на вкладку столбцов «Путь к образу» и «Командная строка», можно нажать на процессе правой кнопкой мыши и выбрать опцию «Открыть место хранения файла» (Open File Location). При этом откроется папка со всеми файлами, относящимися к данному процессу. К примеру, для процесса «hqtray.exe» на моем компьютере открывается папка «VMware Player» (рис. C).

Еще один источник информации о процессе Windows 7 — окно свойств, которое можно вызвать, нажав на процессе правой кнопкой мыши и выбрав опцию «Свойства» (Properties). Полезные сведения содержатся на вкладке «Подробно» (Details, рис. D).

Если вас интересует процесс «Svchost.exe», можно воспользоваться утилитой командной строки Tasklist, чтобы узнать о нем поподробнее. «Svchost.exe» — общее имя процесса для всех служб, запускаемых из динамически подключаемых библиотек (DLL). Чтобы узнать, каким службам принадлежит этот процесс, откройте командную строку (Command Prompt) и выполните следующую команду:

Вы получите список всех запущенных процессов, в котором приводятся сведения о службах для каждого процесса «Svchost.exe» (рис. E).

Узнав имена служб, запомните идентификатор (PID) процесса «Svchost.exe». Теперь откройте вкладку «Службы» (Services) в Диспетчере задач и отсортируйте список по столбцу «ИД процесса» (PID). Найдите нужный идентификатор и посмотрите описание, чтобы понять назначение службы Windows 7 (рис. F).

Сведения, к сожалению, весьма скудные, но хотя бы позволяют понять, какая именно служба запустила процесс «Svchost.exe».

А вам приходилось использовать Диспетчер задач для поиска информации о запущенных процессах Windows 7? Поделитесь своим опытом в комментариях!

Автор: Greg Shultz
Перевод SVET

Оцените статью: Голосов

Источник

Как узнать PID (идентификатор процесса) в Windows

1555418414 get pid process id in windows 1

В данной статье показаны действия, с помощью которых можно узнать PID (идентификатор процесса) в операционной системе Windows.

Идентификатор процесса (process identifier, PID) — уникальный номер процесса в операционной системе Windows.

Все процессы имеют уникальные идентификаторы PID, которые автоматически присваиваются каждому процессу когда он создается в операционной системе, что позволяет ядру системы различать процессы.

При необходимости можно узнать PID (идентификатор процесса).

Как узнать PID (идентификатор процесса) в диспетчере задач

1555418439 get pid process id in windows 2

Теперь найдите нужный процесс, и в столбце ИД процесса будет отображен идентификатор соответствующего процесса.

1555418480 get pid process id in windows 3

Как узнать PID (идентификатор процесса) в командной строке

Также узнать PID (идентификатор процесса) можно используя командную строку.

Запустите командную строку и выполните следующую команду:

Найдите нужный процесс, в столбце PID будет отображен идентификатор процесса.

1555418490 get pid process id in windows 4

Также можно отобразить процессы в виде списка, для этого в командной строке выполните следующую команду:

Найдите нужный процесс, в строке PID будет отображен идентификатор процесса.

1555418402 get pid process id in windows 5

Используя рассмотренные выше действия, можно узнать PID (идентификатор процесса) в операционной системе Windows.

Источник

Finding the process ID

Each process running in Windows is assigned a unique decimal number called the process ID (PID). This number is used in a number of ways, for example to specify the process when attaching a debugger to it.

This topic describes how you can determine the PID for a given app using Task Manager, the tasklist Windows command, the TList utility, or the debugger.

Task Manager

Task Manager can be opened in a number of ways, but the simplest is to select Ctrl+Alt+Delete, and then select Task Manager.

In Windows 10, first click More details to expand the information displayed. From the Processes tab, select the Details tab to see the process ID listed in the PID column.

process id task manager windows 10

Click on any column name to sort. You can right click a process name to see more options for a process.

Some kernel errors may cause delays in Task Manager’s graphical interface.

The tasklist command

Use the built in Windows tasklist command from a command prompt to display all processes, their PIDs, and a variety of other details.

Use tasklist /? to display command line help.

TList utility

Task List Viewer (TList), or tlist.exe, is a command-line utility that displays the list of tasks, or user-mode processes, currently running on the local computer. TList is included in the Debugging Tools for Windows. For information on how to download and install the debugging tools, see Download Debugging Tools for Windows.

If you installed the Windows Driver Kit in the default directory on a 64 bit PC, the debugging tools are located here:

C:Program Files (x86)Windows Kits10Debuggersx64

When you run TList from the command prompt, it will display a list of all the user-mode processes in memory with a unique PID number. For each process, it shows the PID, process name, and, if the process has a window, the title of that window.

For more information, see TList.

The .tlist debugger command

If there’s already a user-mode debugger running on the system in question, the .tlist (List Process IDs) command will display a list of all PIDs on that system.

PowerShell Get-Process command

To work with automation scripts, use the Get-Process PowerShell command. Specify a specific process name, to see the process ID for that process.

For more information, see Get-Process.

CSRSS and user-mode drivers

To debug a user-mode driver running on another computer, debug the Client Server Run-Time Subsystem (CSRSS) process. For more information, see Debugging CSRSS.

Источник

Как узнать какой порт использует программа

На компьютере может быть установлено довольно много программ и все они резервируют в операционной системе определенный порт для взаимодействия с другим программным обеспечением по сети. В большинстве случаев пользователь заранее знает какой порт использует программа. Это может быть официально зарезервированный порт, под определенный сетевой протокол. Например почтовые программы используют для приема почты протокол POP3 и резервируют порт 110. Бывают неофициально резервируемые порты, например порт 1540 используемый агентом сервера 1С:Предприятие. Информацию об используемых неофициальных портах разработчики программного обеспечения указывают в документации.

Определения порта программы стандартными средствами Windows

Поиск идентификатора процесса PID

1. Открываем командную строку: сочетание клавиш и вводим команду CMD.

image 21

2. Запускаем tasklist и находим PID процесса.

Если необходимо отобразить полный список процессов, в том числе служебных и системных, необходимо использовать tasklist без аргументов.

Команда tasklist /fi «status eq running» найдет только те процессы, которые были запущенны программами. Это сократит список процессов и облегчит поиск.

Находим в списке нужную программу, например OneDrive.exe и запоминаем соответствующий PID.

image 23

Поиск порта процесса

Для получения списка используемых портов воспользуемся утилитой командной строки netstat.

B netstat были использованы слtдующие аргументы:

В результате будет получен довольно крупный список активных сетевых соединений, среди которых необходимо найти соединение с нужным PID.

image 25

image 29

В найденных результатах видно, что процесс c PID 15304 (программа OneDrive.exe) использует несколько сетевых портов: 11906, 11907, 11908.

Обращайте внимание на то, для какого траспортного протокола открыт порт: ТСР или UDP. Это информация будет важна, когда будете пробрасывать порт через межсетевой экран.

Программы для просмотра сетевых соединений

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

TCPView

image 31

CurrPorts

Из плюсов программы следует отметить наличие русского языка. Чтобы русифицировать программу нужно скачать отдельный файл русификации и положить его в папку с программой.

image 36

Источник

Поиск и сравнение процесса

Помощь в написании контрольных, курсовых и дипломных работ здесь.

Поиск процесса на c++
ПОМОГИТЕ ПЛИЗ. Программирую на с++ builder 6. Задача: 1-е проверить наличие процесса.

Поиск процесса по имени
Такой вопрос: я ввожу с клавиатуры имя процесса и можно ли проверить, запущен ли процесс с таким.

Поиск процесса по имени
Помогите написать программу поиска процесса по имени на MS Visual Studio 2010.

Добавлено через 1 час 0 минут
Модифицированный вариант с поиском файла в произвольной папке и обработкой каждого найденного PID для найденного имени файлапроцесса:

Решение

Добавлено через 5 минут
что-то типа

чтобы точнее, надо поизучать help по wmic process

Добавлено через 1 минуту
под XP wmic работает,
a ежели чо, проверить наличие SP3.

Добавлено через 4 часа 6 минут
ну вот, появился у меня windows под рукой, поэтому,
чтобы перезапустить процесс, зная его исполняемый путь
doit.bat:

tickПоиск окон процесса
Привет, подскажите пожалуйста какие функции надо использовать в моем случае, никак не могу найти.

tickПоиск процесса по имени
Здравствуйте, помогите пожалуйста перевести с Lua код поиск процесса по имени, на язык.

Поиск процесса по имени
Нужно написать функцию которая будет искать запущен ли процесс (имя процесса за ранние известно).

поиск скрытого процесса.
у меня в системе завёлся скрытый процесс я знаю только имя файла «000.exe» мне надо на нулевом.

Источник

  • Remove From My Forums
  • Question

  • Hi, the main aim is to indentify on which software the user is currently focused on, I’m not so skilled on WinApi and I don’t get how to get the exe filename from there:

    #include <windows.h> #include <stdio.h> #include <tchar.h> #include <psapi.h> #include <iostream> #include <Psapi.h> int main(){ while(1) {
    LPDWORD threadprocessId = 0; printf("pid: %dn", GetWindowThreadProcessId(GetForegroundWindow(), threadprocessId));

    Sleep(1000);

    } }

    • Edited by

      Wednesday, January 3, 2018 1:45 PM

Answers

  • HANDLE hProcess = OpenProcess( PROCESS_ALL_ACCESS | PROCESS_QUERY_INFORMATION |
          PROCESS_VM_READ,
          FALSE, ProcessID );

    Open Process returns NULL and GetLastError() returns 87

    how can I solve?

    The code to obtain the process id is incorrect.

    DWORD tid, pid;
    
    tid = GetWindowThreadProcessId(GetForegroundWindow(), &pid)

    • Marked as answer by
      antonioaltamura
      Wednesday, January 3, 2018 5:53 PM

  • Now the strange thing is if I compile using Dev-C++ IDE I get the full path correctly, if I compile using Visual Studio 2017 I get an exadecimal code..

    ps I noticed I included multiple times some headers it was just a copy/paste mistake in the previous post :)

    Use Unicode Character Set and use

    std::wcout << "nameProcess " << nameProc;

    • Edited by
      Castorix31
      Wednesday, January 3, 2018 1:28 PM
    • Marked as answer by
      antonioaltamura
      Wednesday, January 3, 2018 5:53 PM

  • Very thanks for your help, I mean it.

    So the final working code for future reference is this (using
    -lpsapi param):


    #define UNICODE 1

    #include <windows.h> #include <stdio.h> #include <tchar.h> #include <psapi.h> #include <iostream> #include <WinBase.h> int main() { while (1) { DWORD threadprocessId = 0; DWORD PID; PID = GetWindowThreadProcessId(GetForegroundWindow(), & threadprocessId); printf("pid: %dn", PID); HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS | PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, threadprocessId); if (NULL != hProcess) { std::cout << "hProcess" << hProcess << "n"; TCHAR nameProc[1024]; if (GetProcessImageFileName(hProcess, nameProc, sizeof(nameProc) / sizeof( * nameProc)) == 0) { std::cout << "GetProcessImageFileName Error"; } else { std::wcout << "nameProcess " << nameProc; } } else { printf("OpenProcess(%i) failed, error: %in", PID, (int) GetLastError()); } Sleep(500); } }

    • Marked as answer by
      antonioaltamura
      Wednesday, January 3, 2018 5:53 PM
    • Edited by
      antonioaltamura
      Wednesday, January 3, 2018 6:38 PM

Get-Process [[-Name] <String[]>] [-ComputerName <String[]>] [-FileVersionInfo] [-Module] [<CommonParameters>]
Get-Process [-ComputerName <String[]>] [-FileVersionInfo] -Id* <Int32[]> [-Module] [<CommonParameters>]
Get-Process [-ComputerName <String[]>] [-FileVersionInfo] -InputObject* <Process[]> [-Module] [<CommonParameters>]
Get-Process -Id* <Int32[]> -IncludeUserName* [<CommonParameters>]
Get-Process [[-Name] <String[]>] -IncludeUserName* [<CommonParameters>]
Get-Process -IncludeUserName* -InputObject* <Process[]> [<CommonParameters>]

The Get-Process cmdlet gets the processes on a local or remote computer.

Without parameters, this cmdlet gets all of the processes on the local computer. You can also specify a particular process by process name or process ID (PID) or pass a process object through the pipeline to this cmdlet.

By default, this cmdlet returns a process object that has detailed information about the process and supports methods that let you start and stop the process. You can also use the parameters of the Get-Process cmdlet to get file version information for the program that runs in the process and to get the modules that the process loaded.

Parameters

-ComputerName <String[]>

  • Default value is None
  • Accepts pipeline input ByPropertyName

Specifies the computers for which this cmdlet gets active processes. The default is the local computer.

Type the NetBIOS name, an IP address, or a fully qualified domain name (FQDN) of one or more computers. To specify the local computer, type the computer name, a dot (.), or localhost.

This parameter does not rely on Windows PowerShell remoting. You can use the ComputerName parameter of this cmdlet even if your computer is not configured to run remote commands.

-FileVersionInfo [<SwitchParameter>]

  • Default value is False
  • Accepts pipeline input False

Indicates that this cmdlet gets the file version information for the program that runs in the process.

On Windows Vista and later versions of Windows, you must open Windows PowerShell with the Run as administrator option to use this parameter on processes that you do not own.

You cannot use the FileVersionInfo and ComputerName parameters of the Get-Process cmdlet in the same command. To get file version information for a process on a remote computer, use the Invoke-Command cmdlet.

Using this parameter is equivalent to getting the MainModule.FileVersionInfo property of each process object. When you use this parameter, Get-Process returns a FileVersionInfo object (System.Diagnostics.FileVersionInfo), not a process object. So, you cannot pipe the output of the command to a cmdlet that expects a process object, such as Stop-Process.

-Id <Int32[]>

  • This value is required
  • Default value is None
  • Accepts pipeline input ByPropertyName

Specifies one or more processes by process ID (PID). To specify multiple IDs, use commas to separate the IDs. To find the PID of a process, type `Get-Process`.

-IncludeUserName [<SwitchParameter>]

  • This value is required
  • Default value is False
  • Accepts pipeline input False

Indicates that the UserName value of the Process object is returned with results of the command.

-InputObject <Process[]>

  • This value is required
  • Default value is None
  • Accepts pipeline input ByValue

Specifies one or more process objects. Enter a variable that contains the objects, or type a command or expression that gets the objects.

-Module [<SwitchParameter>]

  • Default value is False
  • Accepts pipeline input False

Indicates that this cmdlet gets the modules that have been loaded by the processes.

On Windows Vista and later versions of Windows, you must open Windows PowerShell with the Run as administrator option to use this parameter on processes that you do not own.

You cannot use the Module and ComputerName parameters of the Get-Process cmdlet in the same command. To get the modules that have been loaded by a process on a remote computer, use the Invoke-Command cmdlet.

This parameter is equivalent to getting the Modules property of each process object. When you use this parameter, this cmdlet returns a ProcessModule object (System.Diagnostics.ProcessModule), not a process object. So, you cannot pipe the output of the command to a cmdlet that expects a process object, such as Stop-Process.

When you use both the Module and FileVersionInfo parameters in the same command, this cmdlet returns a FileVersionInfo object with information about the file version of all modules.

-Name <String[]>

  • Default value is None
  • Accepts pipeline input ByPropertyName

Specifies one or more processes by process name. You can type multiple process names (separated by commas) and use wildcard characters. The parameter name («Name») is optional.

<CommonParameters>

This cmdlet supports the common parameters: Verbose, Debug,ErrorAction, ErrorVariable, WarningAction, WarningVariable,OutBuffer, PipelineVariable, and OutVariable.

Inputs

System.Diagnostics.Process

You can pipe a process object to this cmdlet.

Outputs

System.Diagnostics.Process, System.Diagnotics.FileVersionInfo, System.Diagnostics.ProcessModule

By default, this cmdlet returns a System.Diagnostics.Process object. If you use the FileVersionInfo parameter, it returns a System.Diagnotics.FileVersionInfo object. If you use the Module parameter, without the FileVersionInfo parameter, it returns a System.Diagnostics.ProcessModule object.

Examples
  1. Get a list of all active processes on the local computer:
    PS C:> Get-Process
    

    This command gets a list of all active processes running on the local computer. For a definition of each column, see the «Additional Notes» section of the Help topic for Get-Help.

  2. Get all available data about one or more processes:
    PS C:> Get-Process winword, explorer | Format-List *
    

    This command gets all available data about the Winword and Explorer processes on the computer. It uses the Name parameter to specify the processes, but it omits the optional parameter name. The pipeline operator (|) passes the data to the Format-List cmdlet, which displays all available properties (*) of the Winword and Explorer process objects.

    You can also identify the processes by their process IDs. For instance, `Get-Process -Id 664, 2060`.

  3. Get all processes with a working set greater than a specified size:
    PS C:> Get-Process | Where-Object {$_.WorkingSet -gt 20000000}
    

    This command gets all processes that have a working set greater than 20 MB. It uses the Get-Process cmdlet to get all running processes. The pipeline operator (|) passes the process objects to the Where-Object cmdlet, which selects only the object with a value greater than 20,000,000 bytes for the WorkingSet property. WorkingSet is one of many properties of process objects. To see all of the properties, type `Get-Process | Get-Member`. By default, the values of all amount properties are in bytes, even though the default display lists them in kilobytes and megabytes.

  4. List processes on the computer in groups based on priority:
    PS C:> $A = Get-Process PS C:> Get-Process -InputObject $A | Format-Table -View priority
    

    These commands list the processes on the computer in groups based on their priority class. The first command gets all the processes on the computer and then stores them in the $A variable.

    The second command uses the InputObject parameter to pass the process objects that are stored in the $A variable to the Get-Process cmdlet. The pipeline operator passes the objects to the Format-Table cmdlet, which formats the processes by using the Priority view. The Priority view, and other views, are defined in the PS1XML format files in the Windows PowerShell home directory ($pshome).

  5. Add a property to the standard Get-Process output display:
    PS C:> Get-Process Powershell -ComputerName S1, localhost | ft @{Label="NPM(K)";Expression={[int]($_.NPM/1024)}}, @
    {Label="PM(K)";Expression={[int]($_.PM/1024)}},@{Label="WS(K)";Expression={[int]($_.WS/1024)}},@{Label="VM(M)";Expr
    ession={[int]($_.VM/1MB)}}, @{Label="CPU(s)";Expression={if ($_.CPU -ne $()) { $_.CPU.ToString("N")}}}, Id, MachineName, ProcessName -Auto
    
       NPM(K) PM(K) WS(K) VM(M) CPU(s)   Id MachineName ProcessName
       ------ ----- ----- ----- ------   -- ----------- -----------
       6      23500 31340   142        1980 S1          powershell
       6      23500 31348   142        4016 S1          powershell
       27     54572 54520   576        4428 localhost   powershell

    This example provides a Format-Table (alias = ft) command that adds the MachineName property to the standard Get-Process output display.

  6. Get version information for a process:
    PS C:> Get-Process powershell -FileVersionInfo
    
       ProductVersion   FileVersion      FileName
       --------------   -----------      --------
       6.1.6713.1       6.1.6713.1 (f... C:WINDOWSsystem32WindowsPowerShellv1.0powershell.exe

    This command uses the FileVersionInfo parameter to get the version information for the PowerShell.exe file that is the main module for the PowerShell process.

    To run this command with processes that you do not own on Windows Vista and later versions of Windows, you must open Windows PowerShell with the Run as administrator option.

  7. Get modules loaded with the specified process:
    PS C:> Get-Process SQL* -Module
    

    This command uses the Module parameter to get the modules that have been loaded by the process. This command gets the modules for the processes that have names that begin with SQL.

    To run this command on Windows Vista and later versions of Windows with processes that you do not own, you must start Windows PowerShell with the Run as administrator option.

  8. Find the owner of a process:
    PS C:> $P = Get-WmiObject win32_process -Filter "name='powershell.exe'"
    PS C:> $P.getowner()
    
       __GENUS          : 2
       __CLASS          : __PARAMETERS
       __SUPERCLASS     :
       __DYNASTY        : __PARAMETERS
       __RELPATH        :
       __PROPERTY_COUNT : 3
       __DERIVATION     : {}
       __SERVER         :
       __NAMESPACE      :
       __PATH           :
       Domain           : DOMAIN01
       ReturnValue      : 0
       User             : user01

    This command shows how to find the owner of a process. Because the System.Diagnostics.Process object that Get-Process returns does not have a property or method that returns the process owner, the command uses the Get-WmiObject cmdlet to get a Win32_Process object that represents the same process.

    The first command uses Get-WmiObject to get the PowerShell process. It saves it in the $P variable.

    The second command uses the GetOwner method to get the owner of the process in $P. The command reveals that the owner is Domain01user01.

  9. Use an automatic variable to identify the process hosting the current session:
    PS C:> Get-Process powershell
    
       Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
       -------  ------    -----      ----- -----   ------     -- -----------
       308      26        52308      61780   567     3.18   5632 powershell
       377      26        62676      63384   575     3.88   5888 powershell PS C:>Get-Process -Id $pid
       Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
       -------  ------    -----      ----- -----   ------     -- -----------
       396      26        56488      57236   575     3.90   5888 powershell

    These commands show how to use the $pid automatic variable to identify the process that is hosting the current Windows PowerShell session. You can use this method to distinguish the host process from other Windows PowerShell processes that you might want to stop or close. The first command gets all of the Windows PowerShell processes in the current session.

    The second command gets the Windows PowerShell process that is hosting the current session.

  10. Get all processes that have a main window title and display them in a table:
    PS C:> Get-Process | where {$_.mainWindowTitle} | Format-Table id, name, mainwindowtitle -autosize
    

    This command gets all the processes that have a main window title, and it displays them in a table with the process ID and the process name.

    The mainWindowTitle property is just one of many useful properties of the Process object that Get-Process returns. To view all of the properties, pipe the results of a Get-Process command to the Get-Member cmdlet (get-process | get-member).

Additional Notes
 * You can also refer to this cmdlet by its built-in aliases, ps and gps. For more information, see 
 about_Aliases.

 * On computers that are running a 64-bit version of Windows, the 64-bit version of Windows PowerShell gets 
 only 64-bit process modules and the 32-bit version of Windows PowerShell gets only 32-bit process modules.

 * You can use the properties and methods of the Windows Management Instrumentation (WMI) Win32_Process object 
 in Windows PowerShell. For information, see Get-WmiObject and the WMI SDK.

 * The default display of a process is a table that includes the following columns. For a description of all of 
 the properties of process objects, see Process Propertieshttp://go.microsoft.com/fwlink/?LinkId=204482 at 
 http://go.microsoft.com/fwlink/?LinkId=204482.


 - Handles: The number of handles that the process has opened.

 - NPM(K): The amount of non-paged memory that the process is using, in kilobytes.

 - PM(K): The amount of pageable memory that the process is using, in kilobytes.

 - WS(K): The size of the working set of the process, in kilobytes. The working set consists of the pages of 
 memory that were recently referenced by the process.

 - VM(M): The amount of virtual memory that the process is using, in megabytes. Virtual memory includes storage 
 in the paging files on disk.

 - CPU(s): The amount of processor time that the process has used on all processors, in seconds.

 - ID: The process ID (PID) of the process.

 - ProcessName: The name of the process.

 For explanations of the concepts related to processes, see the Glossary in Help and Support Center and the 
 Help for Task Manager.
 * You can also use the built-in alternate views of the processes available with Format-Table, such as 
 StartTime and Priority, and you can design your own views.

Понравилась статья? Поделить с друзьями:
  • Windows generate ssh key for gitlab
  • Windows home server 2007 скачать торрент
  • Windows insider program windows 10 скачать
  • Windows home server 2007 product key
  • Windows generate ssh key for github