- Get-Process
- Syntax
- Description
- Examples
- Example 1: Get a list of all active processes on the local computer
- Example 2: Get all available data about one or more processes
- Example 3: Get all processes with a working set greater than a specified size
- Example 4: List processes on the computer in groups based on priority
- Example 5: Add a property to the standard Get-Process output display
- Example 6: Get version information for a process
- Example 7: Get modules loaded with the specified process
- Example 8: Find the owner of a process
- Example 9: Use an automatic variable to identify the process hosting the current session
- Example 10: Get all processes that have a main window title and display them in a table
- Parameters
- Inputs
- Powershell скрипты
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.
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.
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.
Powershell скрипты
Доброго времени суток дорогие читатели. В данной статье мы познакомимся с основами Powershell. Данный язык программирования используется во всех ОС Microsoft начиная с Windows XP SP3. Писать Powershell скрипты должен уметь каждый уважающий себя системный администратор windows.
Все команды в Powershell как правило используются в форме командлетов. Все командлеты это специализированные классы .NET Framework и .NET Core (используется в PowerShell Core 6 и выше).
Powershell класса .NET Framework это версии с 1 по 5.1 а Powershell .NET Core это версия 6 и выше (на данный момент 7.0). По заявлению Microsoft новых функций в Powershell 5.1 (.NET Framework) вносить уже не будут. Однако 7 версия еще не полностью поддерживает все модули предыдущих версий. Но судя по всему Microsoft стремится к этому и скоро версия Core будет единственной. В общем cmd отходит в прошлое и теперь без Powershell никуда. Давайте приступим к практике. Так всегда лучше запоминается материал.
Запуск Powershell
На примере Windows 10 Powershell можно запустить просто нажав правой кнопкой мыши на меню пуск.
Также нижняя строчка позволяет запустить Powershell с повышенными правами администратора.
Еще можно воспользоваться поиском в WIndows 10 и ввести название powershell
Как видно на картинке выше нашелся не только Powershell но и Powershell ISE. Консоль powershell удобна если требуется запустить последовательно не больше одной команды. Либо несколько команд в конвейере. Однако в случае написания полноценных скриптов лучше использовать Powershell ISE. Это бесплатная среда разработки сценариев на языке Powershell поставляется вместе с ОС Windows.
Сразу после запуска консоли рекомендую запустить командлет Get-Help – встроенная справка по всем командлетам, аналог man в Linux.
Видим что консоль предлагает обновить встроенную помощь. Нажимаем Y и соглашаемся.
Командлеты
Командлеты – это название команд в Powershell. Каждый командлет реализует заложенную в него функциональность. Как правило наименование командлета состоит из пары: глагол-существительное. Например: Get-Help – получить помощь. Обычно Get используется чтобы получить информация, Set – внести изменение, New – создать новый объект, политику и т.п. и Remove -удалить объект, политику и т.п.
Командлеты не чувствительны к регистру. Написать Get или get не важно, powershell воспримет эти команды одинаково.
Чтобы получить список всех доступных командлетов необходимо использовать Get-Command
Для получения справки по любому командлету напишите Get-Help имя-комндлета. Например
Давайте представим что нам необходимо вывести список командлетов для управления процессами. Воспользуемся Get-Command и укажем ему параметры для более точного поиска.
И вот мы видим список командлетов позволяющих управлять процессами: Get-Process – список всех запущенных процессов, Start-Process – запустить указанный процесс, Stop-Process– остановить указанный процесс, Wait-Process – ожидать указанный процесс. Как видно из названий командлетов можно легко понять для чего каждый служит.
Используя командлет Get-Help можно получить справку по любому командлету.
При использовании командлета есть возможность указать несколько параметров при запуске. Первый параметр можно не называть. Выше я писал Get-Command *Process* где указал поиск командлетов со словом Process. Однако я не написал параметр -Name, хотя именно его и указал. Если полностью то поиск по имени выглядит так: Get-Command -Name *Process* . В случае отсутствия непосредственного указания -Name Powershell принимает в качестве имени введенное слово *Process*.
Давайте выведем список процессов с именем WhatsApp
Мы вывели все процессы с именем WhatsApp и добавили в вывод дополнительный параметр -IncludeUserName, что позволило нам увидеть кем запущен процесс.
Алиасы
Алиасы в Powershell это по сути более короткие названия командлетов. Т.е. любому командлету можно присвоить свое короткое имя (alias). Например алиасом для командлета Get-Process является gps. Согласитесь куда проще и быстрее написать gps чем Get-Process.
Список всех alias можно получить используя командлет Get-Alias
Как видно из списка для alias использованы аналогичные по значению команды из Linux: ls, man, mount, md, kill и т.п. Видимо чтобы линуксоиду было по привычнее 🙂 Можно создать свой alias используя командлет New-Alias
Конвейер
Конвейер используется для передачи выходных данных командлета идущего вначале во входные данные командлета следующего за ним. Ничего непонятно? 🙂 Давайте на примерах, так всегда яснее.
Возьмем уже известный нам командлет Get-Process, посмотрим на его вывод
Как по мне многовато лишних столбцов. Мне эта информация не нужна, поэтому я выберу только нужные данные. Для таких целей служит командлет Select-Object. Давайте используем его в конвейере.
Как вы уже наверно догадались конвейер обозначается знаком | и идет сразу следом за командлетом. И так данные по конвейеру можно передавать и дальше другим командлетам. Итак я передал выходные данные (список запущенных процессов) на вход командлета Select-Object. Который в свою очередь выбрал данные по 3 столбцам ID, CPU, ProcessName. Теперь можно передать эти данные дальше. Например выгрузить в текстовый файл
Просто не правда ли? У нас конвейер из трех командлетов, на выходе которого получаем текстовый файл со списком запущенных процессов и необходимой информацией по ним.
Структура объектов
В Powershell объекты играют самую важную роль. От типа объекта зависит что именно с ним можно сделать. Узнать тип объекта и вывести список всех его элементов позволяет команда Get-Member
Вот далеко не полный список элементов командлета Get-Process. В данному случае тип данных это System.Diagnostics.Process
Давайте посмотрим тип данных у новой переменной
В данном случае тип данных System.String т.е. строка. Что вполне логично. А теперь посмотрите что можно сделать с этой строкой с учетом указанных выше параметров.
Как видно на картинке выше мы заключаем нашу тестовую переменную $new в скобки и после них пишем точку и указываем метод. В примере я использовал три метода:
- ToUpper – перевод всех букв в строке в верхний регистр
- ToLower – перевод всех букв в строке в нижний регистр
- Length – подсчитать количество символов в строке
Это всего лишь небольшой пример что можно сделать с параметрами объекта. Чаще используйте Get-Member и вы откроете для себя безграничные возможности манипуляции над объектами.
Скрипты Powershell
В самом начале статьи указал на встроенный инструмент Powershell ISE. Давайте запустим его и создадим свой первый скрипт. Кстати скрипты сохраняются в файлах с расширением ps1
Скрипт будет запускать блокнот, далее выполняется проверка если блокнот запущен выводится сообщение об этом и после блокнот закрывается. Если блокнот не запущен то выводится соответствующее сообщение об этом. На самом деле блокнот будет всегда запущен, т.к. мы вначале скрипта написали Start-Process notepad
В этом скрипте я использовал цикл if else. О циклах будет подробнее в следующей статье. Итак давайте сохраним скрипт и выполним его.
В ответ мы получим такую ошибку:
Все верно, изначально в WIndows запрещено выполнять скрипты Powershell. Это сделано для повышения безопасности системы. Для включения возможности запуска скриптов Powershell необходимо запустить Powershell от Администратора и ввести командлет Set-ExecutionPolicy с одним из параметров:
- Restricted – политика по умолчанию. Выполнение всех скриптов запрещено
- RemoteSigned – разрешено запускать собственные скрипты и подписанные доверенным разработчиком
- AllSigned – разрешено запускать скрипты, подписанные доверенным разработчиком. Каждый раз перед запуском такого скрипта PowerShell будет запрашивать подтверждение
- Unrestricted – в системе разрешается запускать любые скрипты
Если вы полностью уверены в запускаемых скриптах можете поставить Unrestricted. Давайте так и сделаем
Будет предупреждение по безопасности, соглашаемся нажав Y
Можем посмотреть текущую настройку политики безопасности при помощи командлета Get-ExecutionPolicy
В данной статье мы рассмотрели основы чтобы подготовиться писать скрипты Powershell. В следующих статьях мы более подробно изучим циклы, массивы, функции, работу со строками и много другое. Кстати вот раздел посвященный Powershell. Там много всего интересного 😉