Windows get process list

Как работать с процессами через 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

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

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

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

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

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

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

Управление процессами с помощью PowerShell

PowerShell предоставляет широкие возможности управления процессами на локальном или удаленном компьютере. С помощью PowerShell можно получить список запущенных процессов, приостановить зависший процесс, найти процесс по заголовку окна, запустить новый процесс в скрытом или интерактивном режиме.

Список доступных командлетов управления процессами в Windows 10 можно вывести так:

Читайте также:  Где посмотреть когда включался компьютер windows

Get-Command –Noun Process

  • Get-Process – получить список запущенных процессов;
  • Start-Process – запустить процесс/программу;
  • Stop-Process – принудительно остановить процесс;
  • Debug-Process – используется для отладки процессов;
  • Wait-Process – используется для ожидания окончания процесса.

Get-Process – получение списка запущенных процессов

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

По-умолчанию выводятся следующие свойства запущенных процессов:

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

Чтобы получить все свойства нескольких процессов:

Get-Process winword, notep* | Format-List *

Можно вывести только определенный свойства процессов. Например, имя (ProcessName) время запуска (StartTime), заголовок окна процесса (MainWindowTitle), имя исполняемого файла (Path) и наименование разработчика (Company):

Get-Process winword, notep* | Select-Object ProcessName, StartTime, MainWindowTitle, Path, Company|ft

Вывести список запущенных процессов пользователя с графическими окнами (в список не попадут фоновые и системные процессы):

Get-Process | Where-Object <$_.mainWindowTitle>| Format-Table Id, Name, mainWindowtitle

С помощью параметра IncludeUserName можно вывести имя пользователя (владельца), который запустил процесс:

Get-Process -Name winword -IncludeUserName

С помощью Where-Object можно выбрать процессы в соответствии с заданными критериями. Например, выведем все процессы, которые используются более 200 Мб оперативной памяти, отсортируем процессы в порядке убывания используемого объема RAM, размер памяти из Кб преобразуем в Мб:

Как мы уже говорили ранее командлет Get-Process в параметре CPU содержит время использования процессора конкретным процессом в секундах. Чтобы отобразить процент использования CPU процессами (по аналогии с Task Manager), используйте такую функцию:

function Get-CPUPercent
<
$CPUPercent = @<
Name = ‘CPUPercent’
Expression = <
$TotalSec = (New-TimeSpan -Start $_.StartTime).TotalSeconds
[Math]::Round( ($_.CPU * 100 / $TotalSec), 2)
>
>
Get-Process | Select-Object -Property Name, $CPUPercent, Description | Sort-Object -Property CPUPercent -Descending | Select-Object -First 20
>

Чтобы найти зависшие процессы (которые не отвечают), выполните команду:

Start-Process, Stop-Process: запуск и остановка процессов из PowerShell

Чтобы запустить новый процесс с помощью PowerShell используется команда:

Start-Process -FilePath notepad

Если каталог с исполняемым файлом отсутствует в переменной окружения $env:path, нужно указать полный путь к файлу:

Start-Process -FilePath ‘C:\distr\app.exe’

Можно запустить программу и передать ей аргументы:

Start-Process -FilePath ping -ArgumentList «-n 10 192.168.1.11»

С помощью параметра WindowStyle вы можете задать режим запуска окна процесса (normal, minimized, maximized, hidden). Например, чтобы запустить программу в максимально развернуом окне и дождаться завершения процесса, выполните команду:

Start-Process -FilePath tracert -ArgumentList «192.168.1.11» –wait -windowstyle Maximized

С помощью командлета Stop-Process можно завершить любой процесс. Например, чтобы закрыть все запущенные процессы notepad:

Stop-Process -Name notepad

По-умолчанию не запрашивается подтверждение завершения процесса. Закрываются все процессы, которые соответствуют указанным критериям. Чтобы запросить подтверждение завершения для каждого процесса, добавьте –Confirm.

Stop-Process -Name notepad.exe -Confirm

(Get-Process -Name notepad).Kill()

Из PowerShell можно принудительно завершить все приложения, которые не отвечают диспетчеру процессов Windows:

Get-Process | where-object <$_.Responding -eq $false>| Stop-Process

PowerShell: управление процессами на удаленном компьютере

С помощью аргумента ComputerName командлет Get-Process позволяет управлять процессами на удаленных компьютерах (должен быть включен и настроен WinRM).

Get-Process -ComputerName dc01, dc02| Format-Table -Property ProcessName, ID, MachineName

Если вы хотите завершить процесс на удаленном компьютере, имейте в виду, что у командлета Stop-Process отсутствует параметр –ComputerName. Для завершения процесса на удаленном компьютере можно использовать такой PowerShell код:

$RProc = Get-Process -Name notepad -ComputerName dc01
Stop-Process -InputObject $RProc

Get-Process

Gets the processes that are running on the local computer or a remote 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 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 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

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

The second and third command are another way to find the owner of a process.

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

The third command uses the GetOwner method to get the owner of the process in $p . 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.

Читайте также:  Mmc exe заблокировано администратором windows 10 службы

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

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.

Type: String [ ]
Aliases: Cn
Position: Named
Default value: Local computer
Accept pipeline input: True
Accept wildcard characters: 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 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 .

Type: SwitchParameter
Aliases: FV, FVI
Position: Named
Default value: False
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: False
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.

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