PowerShell предоставляет широкие возможности управления процессами на локальном или удаленном компьютере. С помощью PowerShell можно получить список запущенных процессов, приостановить зависший процесс, найти процесс по заголовку окна, запустить новый процесс в скрытом или интерактивном режиме.
Список доступных командлетов управления процессами в Windows 10 можно вывести так:
Get-Command –Noun Process
- Get-Process – получить список запущенных процессов;
- Start-Process – запустить процесс/программу;
- Stop-Process – принудительно остановить процесс;
- Debug-Process – используется для отладки процессов;
- Wait-Process – используется для ожидания окончания процесса.
Содержание:
- Get-Process – получение списка запущенных процессов
- Start-Process, Stop-Process: запуск и остановка процессов из PowerShell
- PowerShell: управление процессами на удаленном компьютере
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| where-object {$_.WorkingSet -GT 200000*1024}|select processname,@{l="Used RAM(MB)"; e={$_.workingset / 1mb}} |sort "Used RAM(MB)" –Descending
Как мы уже говорили ранее командлет 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
}
Get-CPUPercent
Чтобы найти зависшие процессы (которые не отвечают), выполните команду:
Get-Process | where-object {$_.Responding -eq $false}
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
Мы рассматриваем встроенные возможности комнадлета Get-Process для управления процессами на удаленных компьютерах. Здесь не учитываются возможности PowerShell Remoting, которые доступны в командлетах Invoke-Command и Enter-PSSession.
Если вы хотите завершить процесс на удаленном компьютере, имейте в виду, что у командлета Stop-Process отсутствует параметр –ComputerName. Для завершения процесса на удаленном компьютере можно использовать такой PowerShell код:
$RProc = Get-Process -Name notepad -ComputerName dc01
Stop-Process -InputObject $RProc
Время на прочтение3 мин
Количество просмотров122K
Наверное, все слышали о PowerShell, но наверняка не всем довелось с ним работать. Для тех, кто только начинает прокладывать свой путь в дебри PowerShell, мы приводим перевод поста, вышедшего на портале 4sysops.com. В нем рассказано о 7 командах, которые помогут тем, кто только начал работать с PowerShell. За подробностями – добро пожаловать под кат.
GET-HELP
Самый первый и самый главный командлет PowerShell – вызов справки. С помощью командлета Get-Help можно проверить синтаксис, посмотреть примеры использования и детальное описание параметров любого PowerShell командлета. Этот командлет примечателен тем, что вы просто можете набрать Get-Help Services, чтобы получить список всех командлетов, которые подходят для работы со службами.
Пример:
PS C:\> Get-Help Service
Вы можете выбрать любой командлет из списка, выведенного по запросу выше, чтобы получить справку о нем. Например,
PS C:\> Get-Help -Name Get-Service
Вы получаете всю информацию о командлете Get-Service (будет рассмотрен ниже).
GET-CONTENT
Чтение содержимого файлов – наиболее частое требование для новичков, которые пытаются выучить PowerShell. Процедура чтения файлов с PowerShell упрощается. Даже неспециалист может читать содержимое файла, просто передав его в командлет Get-Content.
Пример.
PS C:\> Get-Content C:\scripts\Computers.txt
mytestpc1
techibee.com
dummynotresolvinghost.com
PS C:\>
Необходимо больше информации о командлете? Воспользуйтесь Get-Help:
PS C:\> Get-Help Get-Content -Detailed
GET-SERVICE
Этот командлет перечисляет все службы, установленные на компьютере. Вы можете использовать его для получения информации о конкретной службе, совокупности служб или просто обо всех службах на компьютере.
Пример:
PS C:\> Get-Service wwansvc, spooler
Status Name DisplayName
------ ---- -----------
Running spooler Print Spooler
Stopped wwansvc WWAN AutoConfig
PS C:\>
Здесь мы запросили информацию о двух службах wwansvc и spooler
Выводится таблица со статусом службы, ее именем и отображаемым именем.
Мы можем видеть что служба spooler запущена, а wwansvc остановлена
STOP-SERVICE И START-SERVICE
Запуск и остановка служб – достаточно важный момент в работе администратора Windows. В PowerShell имеются встроенные командлеты, которые упрощают работу администратора, не требуя открытия консоли MMC. Используя эти командлеты Вы можете останавливать/запускать службы как на локальных, так и на удаленных компьютерах.
Примеры:
Запуск/остановка службы на локальном компьютере (на примере службы spooler):
PS C:\> Stop-Service -Name Spooler
PS C:\> Start-Service -Name Spooler
Запуск/остановка службы на удаленном компьютере (spooler):
PS C:\> $ServiceObj = Get-Service -ComputerName MyPC1 -Name spooler
PS C:\> Stop-Service -InputObj $ServiceObj
PS C:\> Start-Service -InputObj $ServiceObj
GET-PROCESS
Этот командлет позволяет быть в курсе, какие процессы запущены на локальных или удаленных компьютерах. Показываются имя и ID процесса, а также путь к исполняемому файлу, имя компании, версия исполняемого файла и память, используемая процессом.
Примеры:
Получение информации о процессах, запущенных на локальном компьютере:
PS C:\> Get-Process
Введите следующий командлет для получения подробной информации о запущенных процессах
PS C:\> Get-Process | Format-List * -Force
Получение информации о процессах, запущенных на удаленном компьютере:
PS C:\> Get-Process -ComputerName MYPC1 | Format-List * -Force
MYPC1 необходимо заменить на имя того компьютера, с которого вы хотите получить информацию о запущенных процессах.
STOP-PROCESS
Этот командлет остановливает процесс на локальном или удаленном компьютере. Он берет имя или ID процесса и завершает этот процесс. Это полезно в тех случаях, когда приложение не отвечает.
Пример:
Остановить процесс с ID 22608 на локальном компьютере:
PS C:\> Stop-Process -Id 22608
Остановить все процессы Excel на локальном компьютере:
PS C:\> Stop-Process -name excel
Совет: Хотя у командлета Stop-Process отсутствует параметр -ComputerName, Вы все равно можете использовать его для завершения удаленных процессов, используя предложенный ниже совет:
PS C:\> $Obj = Get-Process -Name excel -ComputerName MYPC1
PS C:\> Stop-Process -InputObject $Obj
Upd:
В посте приведен перевод статьи с портала 4sysops.com
Top 7 PowerShell commands for beginners
P.S. Смотрите также интересные посты на Хабре, посвященные работе с PowerShell
Аудит доступа к файлам
Аудит Active Directory (Часть 1 и 2)
Актуализируем учетные данные Active Directory
Аудит создания учетных записей в AD
Interested in using the PowerShell Get-Process cmdlet to display the running processes of a system? With Get-Process you can find the process owner, the process ID, or even where on disk the process is located.
In this article, you will learn how to use PowerShell’s Get-Process cmdlet through real-world examples. If wrangling processes to bend them to your will on Windows or Linux sounds like fun, then keep reading!
Related: How to Kill a Process in Linux Using ps, pgrep, pkill and more!
Prerequisites
Before going any further, below are the necessary prerequisites to follow along with the examples in this article.
- Although Windows PowerShell 5.1 is sufficient for most examples here, PowerShell 7.1 and greater is necessary for Linux support.
Related: Upgrading to PowerShell 7: A Walkthrough
- This article uses Windows 10 and Ubuntu 20.04 LTS, but any OS that PowerShell runs on will work.
Ready? Let’s dive in and manage some processes!
Displaying Running Processes
Get-Process manages local processes. In this first example, you are using the PowerShell Get-Process cmdlet. This command displays all running processes.
Get-Processreturns a point-in-time snapshot of a system’s running process information. To display real-time process information Windows offers Windows Task Manager and Linux offers the top command.
To get started, open up your PowerShell console and run Get-Process. Notice, that Get-Process returns the running process information, as shown below. The output format is identical for the Windows and Linux operating systems.
Get-Process cmdlet on Windows to display local processes.By default, the
gpsorpsexist as command aliases forGet-Process. As PowerShell 7 is cross-platform, thepscommand conflicts with a built-in Linux command. Thereforepswill not work on Linux, only thegpsalias.
The meaning of Get-Process output may not be immediately obvious. The default Get-Process properties are described in more detail below.
- NPM(K) – The amount of non-paged memory a process is using, displayed in kilobytes, as indicated by the
(K)notation. - PM(M) – The amount of pageable memory a process is using, displayed in megabytes, as indicated by the
(M)notation. - WS(M) – The size of the working set of the process, displayed in megabytes. 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, displayed in megabytes. Includes storage in the paging files on disk.
- CPU(S) – The amount of processor time that the process has used on all processes, displayed in seconds.
- Id – The process ID (PID) of the process.
- SI – Session Identifier of the running process. Session
0indicates the process is available for all users,1indicates the process exists under the first logged in user, and so on. - ProcessName – The name of the running process.
To display a list of property aliases mapped to full property names, use the command
Get-Process | Get-Member -MemberType 'AliasProperty'.
Below is another great example. For each instance of the brave process it finds, it uses that process’s ID ($_.id) and passes it to Get-NetTCPConnection. PowerShell then uses Get-NetTCPConnection to find information about each network connection the brave process has open.
Run the following code in your PowerShell session when the Brave browser is running.
Get-Process -Name brave | ForEach-Object { Get-NetTCPConnection -OwningProcess $_.Id -ErrorAction SilentlyContinue }
Thank you to Jay Adams over at SystemFrontier!
Congratulations, you can now view all the running processes on both Windows and Linux using Get-Process!
Finding Specific Process Attributes
Get-Process returns many different properties on running processes as you have seen earlier. Like with all other PowerShell objects, you can selectively pick out properties on objects.
Let’s now step through a simple example of how you can retrieve specific properties for a specific process:
- Fire up your Windows calculator.
2. With a PowerShell console open, run Get-Process using the Name parameter to only show all running processes with Calculator as the name. You’ll see the same output you’ve seen previously.
Get-Process -Name 'Calculator'
Get-Process returns many properties as expected. Maybe you only want to find CPU utilization with the value under the CPU(s) column. Surround the Get-Process command with parentheses and reference the CPU property as shown below. You’ll see that it only returns the value for the CPU property.
(Get-Process -Name 'Calculator').CPU
Notice that
Get-Processreturns a name calledCPU(s)and the code snippet above used the name of justCPU. Sometimes PowerShell doesn’t show the real property name in the output. This concept is performed with a PS1XML formatting file.
The CPU time is expressed as a total of seconds across cores. To get that to a more human-readable number, round it to the nearest tenth using a Math method as shown below.
$cpu = (Get-Process -Name 'Calculator').CPU
[math]::Round($cpu,2)
You can use the above approach to find any other properties too like
Idif you’d like to only see a process’ ID.
Leave the Calculator application running. You’ll be using this application for the remainder of the examples.
Retrieving Process Memory Usage
Troubleshooting slow running systems can be a challenge, with constrained memory often a cause. Continuing with the Calculator app, retrieve the Calculator process, and display only the VM property. As seen below, the memory used is displayed in megabytes (MB).
(Get-Process -Name 'Calculator').VM
Calculator process memory usage.To aid in understanding the memory usage, utilize the built-in PowerShell conversion multipliers to change megabytes (MB) to gigabytes (GB). In the below example, you will convert the memory used to GB and then use the .NET math library Round method to round the value, as seen in the below screenshot.
$ProcessMemoryGB = (Get-Process -Name 'Calculator').VM
$ProcessMemoryGB / 1GB
# Use the .NET Math type Round method
[Math]::Round($ProcessMemoryGB / 1GB)
Using built-in PowerShell utilities to convert the values makes it easier to understand the output. Read on to learn how to locate a process’s ID.
Exposing Lesser-Known Properties
Not all properties are included or shown by default with Get-Process. Read on below to learn more about the Path and UserName properties and how to use them!
Discovering Where a Process Binary Lives
There are many places on a system that a process executable can be stored. If a process is currently running, Get-Process makes finding the process file system path easy, despite Path not displaying by default. As shown below, the Path property contains the filesystem location of the process executable.
(Get-Process -Name 'Calculator').Path
Get-Process to display a process’s full file system path on Windows.Just as in Windows, Get-Process in Linux also returns the filesystem path. In the example below, the gnome-calculator process is running with the path displayed in the console output.
(Get-Process -Name 'gnome-calculator').Path
Get-Process to display a process’s full file system path on Linux.Crafty bad actors may name a process the same or similar as a trusted one. Therefore, the ability to locate the filesystem path aids in a security incident response (IR) scenario. Read on to discover how to locate the process owner, as UserName is not included in the default output.
Finding the Process Owner
To include the UserName value in the output, you will need to use the IncludeUserName parameter. It is important to know the process owner, especially to avoid unwittingly terminating another user’s process. As shown below, the UserName property is now included in the process output.
Get-Process -Name 'Calculator' -IncludeUserName
Calculator process on Windows.Finally, read on to learn about using Get-Process on a remote computer to retrieve process information!
Finding Processes on Remote Computers
Although in Windows PowerShell, Get-Process doesn’t have any remote capabilities on its own, you can always leverage PowerShell Remoting and the Invoke-Command to run it on remote computers.
Related: How to Set up PSRemoting with Windows and Linux
But, if you’re on Linux or are running PowerShell 6 on Windows, you now have a ComputerName parameter you can use to query processes on remote computers.
Get-Process -ComputerName 'remote_computer_name' -ProcessName 'process'
The
-ComputerNameparameter was removed in PowerShell 7.x as the cmdlet is not directly related to remoting. To achieve the same, you can wrap the same in anInvoke-Command, like so:Invoke-Command -ComputerName "ComputerName" -ScriptBlock { Get-Process -ProcessName 'process' }
When the above command is run against a remote computer, the same output is shown as if the Get-Process command was run locally.
Below is an example of remoting to another computer and getting running processes:
You can target multiple computers by separating them with a comma e.g.
Get-Process -ComputerName SRV1,SRV2.
Next Steps
In this article, you’ve learned how to use the PowerShell Get-Process cmdlet to find running processes with PowerShell on local and remote computers both Linux and Windows.
Now, what will you do with this knowledge? Try passing a process retrieved by Get-Process to Stop-Process on a local or remote computer to terminate!
Все способы:
- Способ 1: «Диспетчер задач»
- Способ 2: «PowerShell»
- Способ 3: «Командная строка»
- Способ 4: Сторонние приложения
- Вопросы и ответы: 0
Способ 1: «Диспетчер задач»
Для просмотра процессов и управления ими в Windows 10 предусмотрено штатное приложение «Диспетчер задач». Его использование является самым простым, удобным и наглядным способом получения сведений о запущенных в системе системных и сторонних процессов.
- Откройте «Диспетчер задач» из контекстного меню «Панели задач» или любым другим удобным вам способом.
Подробнее: Способы открыть «Диспетчер задач» в Windows 10
- Список процессов, а если точнее, их названий, доступен для просмотра в одноименной вкладке: в ней будет указан уровень загрузки ЦП, ОЗУ, диска и сети для каждого процесса.
- Если слева от имени процесса располагается импровизированная стрелка, значит, процесс содержит один и более подпроцессов. Кликните по стрелке, чтобы просмотреть подпроцессы.
Просмотреть процессы в «Диспетчере задач» можно также на вкладке «Подробности». Здесь, помимо исполняемого файла процесса, для просмотра доступны такие данные, как его идентификатор, состояние, владелец, используемый объем памяти и название.
Способ 2: «PowerShell»
Вывести список запущенных процессов можно также с помощью консоли «PowerShell». Способ хорош тем, что позволяет получать дополнительные данные о процессах и гибко сортировать их при необходимости.
- Откройте консоль «PowerShell» от имени администратора из контекстного меню кнопки «Пуск».
- Введите в консоли команду
Get-Processи нажмите клавишу ввода.
В результате вы получите список процессов с указанием таких свойств, как количество дескрипторов ввода («Handles»), выгружаемый и невыгружаемый размер данных процесса «(PM(K) и NPM(K))», объем используемой процессом памяти («WS(K)»), процессорное время («CPU(s)») и идентификатор («ID»). Имя процесса будет указано в столбце «ProcessName».
Способ 3: «Командная строка»
Для получения списка процессов сгодится и классическая «Командная строка», однако в этом случае вы получите несколько меньший объем свойств процессов.
- Откройте «Командную строку» от имени администратора через поиск или другим известным вам методом.
Подробнее: Открытие «Командной строки» в Windows 10
- Выполните команду
tasklist.
В результате, помимо названий процессов, вы получите следующие сведения: идентификаторы, имя сессии, номер сеанса и объем ОЗУ, потребляемый каждым процессом.
Способ 4: Сторонние приложения
Если вы хотите получить о запущенных процессах максимум деталей, лучше использовать специализированные сторонние программы, например Process Explorer — мощный бесплатный инструмент управления процессами.
Скачать Process Explorer с официального сайта
- Скачайте исполняемый файл утилиты procexp.exe или procexp64.exe и запустите.
- Если до этого программа никогда не запускалась, вам будет предложено принять лицензионное соглашение.
- В результате в левой колонке приложения будет выведен список всех запущенных на компьютере процессов. Если нужно просмотреть свойства процесса, кликните по нему два раза мышкой.
Одним лишь просмотром процессов и их свойств возможности Process Explorer не ограничиваются. С помощью этой небольшой портативной программы вы можете принудительно завершать работу процессов, изменять их приоритет, создавать дампы памяти, выявлять связанные динамические библиотеки, а также выполнять другие операции.
Наша группа в TelegramПолезные советы и помощь
-
Use the
Get-ProcessCmdlet to Show a List of Running Processes in PowerShell -
Conclusion
This article delves into the utilization of PowerShell for process monitoring, emphasizing the Get-Process cmdlet. The Get-Process cmdlet, a staple in process management, offers a comprehensive view of running processes on a Windows machine, displaying critical information like process IDs, names, memory usage, and CPU consumption.
The article methodically unfolds the cmdlet’s syntax and parameters, catering to both general and specific process inquiries.
Use the Get-Process Cmdlet to Show a List of Running Processes in PowerShell
There are more than 200 cmdlets available in the PowerShell environment. Each cmdlet is responsible for performing a specific function.
The Get-Process is one of the frequently used cmdlets that help retrieve the list of running processes on the Windows machine.
This cmdlet gives useful information related to each process, such as process ID, name, memory usage, etc. Also, it shows a snapshot of the system’s running processes.
Syntax:
Get-Process [[-ProcessName] string[]] [-NameOfTheComputer string[]]
[-FileVersionInfo] [-Module] [CommonParameters]
Get-Process -processID Int32[] [-ComputerName string[]]
[-FileVersionInfo] [-Module] [CommonParameters]
Get-Process -ProcessInputObject Process[] [-ComputerName string[]]
[-FileVersionInfo] [-Module] [CommonParameters]
Parameters:
ProcessName string[]: Specifies an array of process names to get. This parameter accepts wildcard characters for pattern matching. If this parameter is omitted,Get-Processretrieves all processes.ProcessId Int32[]: Specifies the process IDs of the processes to be retrieved. This parameter allows you to target specific processes directly.InputObject Process[]: Specifies an array of process objects. This parameter allows you to pipe process objects toGet-Process.NameOfTheComputer string[]: Indicates the name(s) of the computers on which to run the command. If this parameter is omitted,Get-Processretrieves processes from the local computer.FileVersionInfo: Adds file version information to the process objects. This is useful when you want details about the executable file of the process, such as version, product name, etc.Module: Includes the modules (DLLs and executable files) that are loaded by each process. This is helpful for more detailed analysis, such as checking which DLLs are loaded by a process.[CommonParameters]: These are the parameters that all cmdlets support, such as-Verbose,-Debug,-ErrorAction,-ErrorVariable,-OutVariable,-OutBuffer, and-PipelineVariable.
The parameters are optional to the Get-Process cmdlet, and you can use those parameters based on your requirements.
Display All the Running Processes
We can directly use the Get-Process command without any parameters. It should display all the running processes at that time.
Also, the gps alias can be used instead of the Get-Process command.
Output:
Upon executing either Get-Process or gps, PowerShell begins a system-wide query to gather information about all active processes. The absence of parameters in these commands signals PowerShell to not apply any filters and retrieve details for every process.
PowerShell then collects detailed data about each running process. This data includes various attributes that describe the state and characteristics of these processes.
PowerShell formats it into a table for display. This tabular format is designed to present the information in a clear and readable manner.
The table typically includes several key columns:
Id: This column shows the Process Identifier (PID), a unique numerical label assigned to each process. ThePIDis crucial for uniquely identifying and managing specific processes.ProcessName: This is the name of the executable file that initiated the process. It helps in easily recognizing the process, especially for well-known applications.CPU(s): Here, we see the amount of CPU time the process has consumed. This is measured in seconds and is vital for assessing which processes are using significant CPU resources, potentially impacting system performance.PM(K): This stands forPaged Memoryin Kilobytes. It represents the size of memory the process is using that can be paged to disk. This metric is important for monitoring the memory usage of processes, which is crucial for performance tuning and resource management.
Retrieve the Information for a Single Process
When using PowerShell to retrieve information about a specific process, we have a couple of syntax options. Both Get-Process -Name processName and Get-Process processName are valid and achieve the same result, but they slightly differ in their syntax structure.
OR
When we execute either Get-Process -Name typora or Get-Process typora, PowerShell filters the running processes and returns information specifically for the process named typora. This is particularly useful when we know the exact name of the process we’re interested in.
Under the hood, PowerShell looks through the list of all processes and matches the process name with typora. If the process is running, its details are displayed.
Output:
Retrieve the Information for Multiple Processes
When we use the Get-Process cmdlet in PowerShell to retrieve information for multiple processes, as in the command Get-Process NotePad, Outlook, we’re leveraging PowerShell’s capability to handle multiple items simultaneously.
Get-Process NotePad, Outlook
By running Get-Process NotePad, Outlook, we instruct PowerShell to fetch details for multiple processes simultaneously, in this case, NotePad and Outlook. This command is handy when we need to monitor several specific processes.
PowerShell executes a similar operation as the single-process command but for each specified process name, displaying all matches.
Output:
Also, you can use the wild cards for the process name.
Retrieve Process Objects With the Given Attributes
We can display the process object information for specific attributes when needed. Let’s retrieve only the Process ID for the NotePad process.
In the command (Get-Process NotePad).Id, we first get the process object for NotePad and then access its Id property. This technique is useful when we’re only interested in specific information about a process, such as its Process ID.
Output:
Also, we can retrieve the CPU time attribute for the NotePad process, as shown in the following.
(Get-Process NotePad).CPU
Similarly, (Get-Process NotePad).CPU retrieves the CPU usage information for the NotePad process. These commands demonstrate how we can extract particular data points from the process objects.
Output:
Display the Process Owner
The default output of the Get-Process command doesn’t display the ProcessOwner attribute. But this can be a piece of valuable information when you need to terminate a given process.
We can use the -IncludeUserName parameter to include the ProcessOwner attribute in the output.
Get-Process -Name notepad -IncludeUserName
The command Get-Process -Name notepad -IncludeUserName extends the default behavior of Get-Process by including the process owner’s username in the output. The -IncludeUserName parameter is essential when we need to identify which user is running a specific process, which can be critical in multi-user environments or for troubleshooting.
This command enhances our visibility into the processes, especially regarding their ownership.
Output:
Conclusion
This comprehensive guide has illuminated the power and versatility of PowerShell in managing and monitoring system processes. We’ve journeyed through the practical applications of the Get-Process cmdlet, starting from listing all running processes to pinpointing specific ones and delving into the extraction of particular process attributes.
The article also showcased the adeptness of PowerShell in handling multiple processes simultaneously and the ease of integrating user-centric information such as process ownership.
This integration of the Get-Process cmdlet underscores PowerShell’s robustness and adaptability in the realm of process management, offering a spectrum of tools for system administrators to monitor, analyze, and manage processes effectively within a Windows environment.
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
