Get process ids windows

Как работать с процессами через Powershell Get-Process

Командлет Powershell Get-Process возвращает все процессы запущенные на локальном компьютере. Команда пишется так:

Мы так же можем посмотреть так же процессы, запущенные на удаленном компьютере:

Но для того, что бы мы смогли это сделать удаленно у нас минимум должен быть включен WinRM. Если вы впервые слышите об этом, то вы можете прочитать об этом в этой статье. Так же добавлю, что ключ -ComputerName частый признак того, что мы можем выполнить команду удаленно.

Навигация по посту

Скорее всего мы хотим получить более детальную информацию или отфильтровать её. Если мы хотим получить информацию об экземплярах, достаточно заполнить ключ -Name:

Где:
-IncludeUserName — выведет имя того, кто запустил экземпляр.

Если мы не знаем имени, можно добавить * :

При этом если у вас запущено несколько процессов с этим именем, вернуться все.

Расшифрую заголовки:

  • Handles — Дескриптор процесса, кто-то может знать под HWND. Уникальное число потока ввода — вывода.
  • NPM(K) — Non-paged memory. Данные, которые не выгружаются на диск в килобайтах.
  • PM(K) — Pageable memory. Данные, которые могут быть выгружены на диск в килобайтах.
  • WS(K) — Process working set. Рабочий набор процесса или сумма всех страниц, которые на данный момент находятся в памяти в килобайтах.
  • CPU(s) — время использованное процессом на всех процессорах в секундах.
  • ID — идентификатор процесса, мы по нему можем фильтровать.
  • SI — Session ID. Идентификатор сеанса где 0 — запущен для всех сессий, 1 — запущен для первого залогиненного пользователя, 2 — для следующего.

Попробуем преобразовать значение из килобайтов в мегабайты:

Где:
-Select-Object обозначаем столбцы, которые хотим вывести.

Как вывести детальную информацию через Powershell Get-Process

Что бы вывести всю возможную информацию два варианта. Это либо вывести объект в виде листа:

Либо можно объявить в переменную, получить все имена свойств и вызывать их по отдельности:

Под такой командой powershell я могу узнать имя, которое пишется в окошке:

Свойств, которые хранит объект процесса (то что мы видим при $result | Get-Member) очень много и это главное, к чему нужно обращаться когда мы хотим узнать подробнее об объекте.

Так мы выведем все запущенные процессы, у которых есть GUI:

Как отфильтровать процессы по утилизации в Powershell

Так мы увидим процессы, которые используют больше 67 Мб в памяти с дополнительной информацией о приоритете:

Таким командлетом мы получи информацию по одному процессу, у которого самое высокое значение CPU. Из свойств этого объекта выбран ID, Имя, CPU и время запуска.

Запуск и остановка процессов через Powershell

Мы можем остановить любой процесс. Например таким образом мы остановим все процессы, которые не отвечают (зависли):

Читайте также:  Failed to save the document permission denied kali linux

Конечно мы можем остановить процесс по идентификатору или имени:

Таким командлетом мы остановим самый старый процесс:

Запуск экземпляра и его завершение через 5 секунд:

Все остальные команды можно узнать с помощью:

Справки с вариантами использования команд powershell:

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.

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 Kits\10\Debuggers\x64\

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.

Get-Process

Gets the processes that are running on the local computer.

Syntax

Description

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.

Читайте также:  Визуал студио для windows 10

Examples

Example 1: Get a list of all active processes on the local computer

This command gets a list of all active processes running on the local computer. For a definition of each column, see the Notes section.

Example 2: Get all available data about one or more processes

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 .

Example 3: Get all processes with a working set greater than a specified size

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.

Example 4: List processes on the computer in groups based on 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 pipes the Process object stored in the $A variable to the Get-Process cmdlet, then 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 PowerShell home directory ( $pshome ).

Example 5: Add a property to the standard Get-Process output display

This example retrieves processes from the local computer and a remote computer (S1). The retrieved processes are piped to the Format-Table command that adds the MachineName property to the standard Get-Process output display.

Example 6: Get version information for a process

This command uses the FileVersionInfo parameter to get the version information for the pwsh.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 PowerShell with the Run as administrator option.

Example 7: Get modules loaded with the specified process

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 PowerShell with the Run as administrator option.

Example 8: Find the owner of a process

This command shows how to find the owner of a process. On Windows, the IncludeUserName parameter requires elevated user rights (Run as Administrator). The output reveals that the owner is Domain01\user01.

Example 9: Use an automatic variable to identify the process hosting the current session

These commands show how to use the $PID automatic variable to identify the process that is hosting the current PowerShell session. You can use this method to distinguish the host process from other PowerShell processes that you might want to stop or close.

Читайте также:  Python subprocess linux command

The first command gets all of the PowerShell processes in the current session.

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

Example 10: Get all processes that have a main window title and display them in a table

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 .

Parameters

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 PowerShell with the Run as administrator option to use this parameter on processes that you do not own.

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 .

Type: SwitchParameter
Aliases: FV, FVI
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False

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 .

Type: Int32 [ ]
Aliases: PID
Position: Named
Default value: None
Accept pipeline input: True
Accept wildcard characters: False

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

Type: SwitchParameter
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False

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

Type: Process [ ]
Position: Named
Default value: None
Accept pipeline input: True
Accept wildcard characters: 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 PowerShell with the Run as administrator option to use this parameter on processes that you do not own.

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.

Type: SwitchParameter
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False

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.

Type: String [ ]
Aliases: ProcessName
Position: 0
Default value: None
Accept pipeline input: True
Accept wildcard characters: True

Inputs

You can pipe a process object to this cmdlet.

Оцените статью