PowerShell: Process Wrangling with Get-Process

PowerShell: Process Wrangling with Get-Process

The PowerShell command Get-Process will return all running processes similar to the tasklist command. In this article, we will explore all the powerful ways to use the Get-Process command.

The Basics

Get-Process

List all running processes 

PS C:\dev\playground> Get-Process

Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
-------  ------    -----      -----     ------     --  -- -----------
    479      45    72088      95316       5.05  16984   9 Adobe CEF Helper
    901      56    84624     122208      38.19  11072   9 Adobe Desktop Service
    244      18     5232      11524       7.73   9776   9 AdobeIPCBroker
    267      17     3732      10908       0.66   3452   0 AdobeUpdateService
    115       9     1828       2264       0.08  13584   0 svchost
    134       9     1844       7640       0.06  14116   0 svchost
    235      16     2856      10928       3.23  15936   0 svchost
   4848       0      184      18136   3,883.41      4   0 System
    483      37     9264      23040       1.78  10000   9 taskhostw
    115       7     1696       7088       0.05   1536   9 unsecapp
    668      22    10268      21888      21.17   5968   0 WmiPrvSE
    378      17    26128      10260       2.16   1348   0 WUDFHost
    328      19     6272      14144       5.94   4052   0 ZeroConfigService
### output truncated

Get-Process explorer

Get process(es) by name.
Note: This command may return more than one result if multple instances of an application are running.

Get-Process a*

Wildcard Query search for processes by name 

PS C:\dev\playground> Get-Process a*

Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
-------  ------    -----      -----     ------     --  -- -----------
    479      45    72208      95800       6.20  16984   9 Adobe CEF Helper                   
    912      56    84628     122356      54.34  11072   9 Adobe Desktop Service                   
    244      18     5584      11776      13.14   9776   9 AdobeIPCBroker                   
    267      17     3732      10908       0.72   3452   0 AdobeUpdateService                   
    205      13     4732      11212      24.34   3520   0 AGSService                   
    219      20     3888      13388       6.70  16040   0 AppleMobileDeviceService                   
    632      38    13168      37336       1.89   9912   9 ApplePhotoStreams                   
    364      25     4984      17416       0.42   9764   9 APSDaemon                   
    516      23    30828      35288   3,189.81  14576   0 audiodg                   

Get-Process -Id 3916

Get process by id or PID

Get-Process -iD 3916 | Select-Object *

Get all available information about a single process. 

PS C:\dev\playground> Get-Process -iD 3916 | Select-Object *


Name                       : WavesSysSvc64
Id                         : 3916
PriorityClass              : Normal
FileVersion                : 1.1.6.0
HandleCount                : 97
WorkingSet                 : 3276800
PagedMemorySize            : 2433024
PrivateMemorySize          : 2433024
VirtualMemorySize          : 36986880
TotalProcessorTime         : 00:00:00.0312500
SI                         : 0
Handles                    : 97
VM                         : 36986880
WS                         : 3276800
PM                         : 2433024
NPM                        : 8624
Path                       : C:\Program Files\Waves\MaxxAudio\WavesSysSvc64.exe
Company                    : Waves Audio Ltd.
CPU                        : 0.03125
ProductVersion             : 1.1.6.0
Description                : WavesSysSvc Service Application
Product                    : Waves MaxxAudio
__NounName                 : Process
BasePriority               : 8
ExitCode                   : 
HasExited                  : False
ExitTime                   : 
Handle                     : 1896
SafeHandle                 : Microsoft.Win32.SafeHandles.SafeProcessHandle
MachineName                : .
MainWindowHandle           : 0
MainWindowTitle            : 
MainModule                 : System.Diagnostics.ProcessModule (WavesSysSvc64.exe)
MaxWorkingSet              : 1413120
MinWorkingSet              : 204800
Modules                    : {System.Diagnostics.ProcessModule (WavesSysSvc64.exe), System.Diagnostics.ProcessModule (ntdll.dll), 
                             System.Diagnostics.ProcessModule (KERNEL32.DLL), System.Diagnostics.ProcessModule (KERNELBASE.dll)...}
NonpagedSystemMemorySize   : 8624
NonpagedSystemMemorySize64 : 8624
PagedMemorySize64          : 2433024
PagedSystemMemorySize      : 62752
PagedSystemMemorySize64    : 62752
PeakPagedMemorySize        : 5505024
PeakPagedMemorySize64      : 5505024
PeakWorkingSet             : 8888320
PeakWorkingSet64           : 8888320
PeakVirtualMemorySize      : 40390656
PeakVirtualMemorySize64    : 40390656
PriorityBoostEnabled       : True
PrivateMemorySize64        : 2433024
PrivilegedProcessorTime    : 00:00:00.0312500
ProcessName                : WavesSysSvc64
ProcessorAffinity          : 255
Responding                 : True
SessionId                  : 0
StartInfo                  : System.Diagnostics.ProcessStartInfo
StartTime                  : 9/30/2017 4:33:01 PM
SynchronizingObject        : 
Threads                    : {3920, 5108}
UserProcessorTime          : 00:00:00
VirtualMemorySize64        : 36986880
EnableRaisingEvents        : False
StandardInput              : 
StandardOutput             : 
StandardError              : 
WorkingSet64               : 3276800
Site                       : 
Container                  : 

Get-Process explorer -IncludeUsername

Information about the process owner is not included in the output by default but can be by supplying the -IncludeUserName argument. 

PS C:\dev\playground>  Get-Process explorer -IncludeUsername | Select-Object Id,Name,UserName

  Id Name     UserName
  -- ----     --------
7628 explorer MYCOMPUTER\me

Get-Process -FileVersionInfo explorer | Select-Object *

Use the -FileVersionInfo argument to get detailed information about a executable file for a given process.
Note: Omitting | Select-Object * only returns ProductVersion,FileVersion,FileName. 

PS C:\dev\playground> Get-Process -FileVersionInfo explorer | Select-Object *

FileVersionRaw     : 10.0.15063.608
ProductVersionRaw  : 10.0.15063.608
Comments           : 
CompanyName        : Microsoft Corporation
FileBuildPart      : 15063
FileDescription    : Windows Explorer
FileMajorPart      : 10
FileMinorPart      : 0
FileName           : C:\WINDOWS\Explorer.EXE
FilePrivatePart    : 608
FileVersion        : 10.0.15063.0 (WinBuild.160101.0800)
InternalName       : explorer
IsDebug            : False
IsPatched          : False
IsPrivateBuild     : False
IsPreRelease       : False
IsSpecialBuild     : False
Language           : English (United States)
LegalCopyright     : © Microsoft Corporation. All rights reserved.
LegalTrademarks    : 
OriginalFilename   : EXPLORER.EXE.MUI
PrivateBuild       : 
ProductBuildPart   : 15063
ProductMajorPart   : 10
ProductMinorPart   : 0
ProductName        : Microsoft® Windows® Operating System
ProductPrivatePart : 608
ProductVersion     : 10.0.15063.0
SpecialBuild       : 


Working with multiple instances of an application

Get-Process notepad | Sort-Object StartTime | Select-Object Id,Name,StartTime

List all instances of an application sorted by StartTime. 

PS C:\dev\playground> Get-Process notepad | Sort-Object StartTime | Select-Object Id,Name,StartTime

   Id Name    StartTime           
   -- ----    ---------           
12524 notepad 10/7/2017 1:35:24 PM
 7708 notepad 10/7/2017 1:35:31 PM
 5380 notepad 10/7/2017 1:35:37 PM
17424 notepad 10/7/2017 1:35:46 PM
11336 notepad 10/7/2017 1:35:53 PM

Get-Process notepad | Sort-Object StartTime | Select-Object Id,Name,StartTime | Select -First 1

Get the longest running instances of an application. 

PS C:\dev\playground> Get-Process notepad | Sort-Object StartTime | Select-Object Id,Name,StartTime | Select -First 1

   Id Name    StartTime           
   -- ----    ---------           
12524 notepad 10/7/2017 1:35:24 PM

Get-Process notepad | Sort-Object StartTime -Descending | Select-Object Id,Name,StartTime | Select -First 1

Get the most recent running instances of an application. 

PS C:\dev\playground> Get-Process notepad | Sort-Object StartTime -Descending | Select-Object Id,Name,StartTime | Select -First 1

   Id Name    StartTime           
   -- ----    ---------           
11336 notepad 10/7/2017 1:35:53 PM


User Processes

Get Processes by Username

# Get Logged In User
$myuser = $(Get-WMIObject -class Win32_ComputerSystem | select username).username

# Query for User Processes
Get-Process -IncludeUserName | Where-Object {$_.UserName -eq $myuser}

Process CPU and Memory Utilization

Get-Process | Sort-Object CPU -desc | Select-Object -first 5 | Format-Table Id,ProcessName,CPU

Get top 5 processes by CPU utilization 

PS C:\dev\playground> Get-Process | Sort-Object CPU -desc | Select-Object -first 5 | Format-Table  Id,ProcessName,CPU 

   Id ProcessName           CPU
   -- -----------           ---
    4 System         4038.09375
14576 audiodg         3016.0625
 3608 KillerService   2674.9375
 5632 WmiPrvSE      2331.890625
12156 chrome        1474.921875633.328125 KillerService
2303.109375 WmiPrvSE     
1373.234375 chrome       

gwmi Win32_PerfFormattedData_PerfProc_Process| sort PercentProcessorTime -desc | select IDProcess,Name,PercentProcessorTime | Select -First 7 | ft -auto

This alternative command does not use Get-Process but does show top 5 processes with percentage of CPU utilization. 

PS C:\dev\playground> gwmi Win32_PerfFormattedData_PerfProc_Process| sort PercentProcessorTime -desc | select IDProcess,Name,PercentProcessorTime | Select -First 7 | ft -auto

IDProcess Name      PercentProcessorTime
--------- ----      --------------------
        0 _Total                     100
        0 Idle                       100
    12156 chrome#20                   17
    17760 chrome#23                   11
     9880 chrome#24                   11
    14576 audiodg                     11
     1168 chrome#21                    5

get-process | Where-Object {$_.Responding -ne "True"}

List all process that are hung or not responding. 

PS C:\dev\playground> get-process | Where-Object {$_.Responding -ne "True"}

Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName                                                                                             
-------  ------    -----      -----     ------     --  -- -----------                                                                                             
   1233      44    37768      92448       6.86  10804   9 ShellExperienceHost                                                                                     
    667      35    15172      44736       0.88   6688   9 SystemSettings                                                                                          

Get-Process | Where-Object {$_.WorkingSet -gt 100000000}

Get all processes using more than 100MB of memory 

PS C:\dev\playground> Get-Process | Where-Object {$_.WorkingSet -gt 100000000}

Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
-------  ------    -----      -----     ------     --  -- -----------
    909      56    84628     122312      48.98  11072   9 Adobe Desktop Service
    448      65   234176     256376     244.64   1168   9 chrome
   3253     123   289692     375732     970.67   3060   9 chrome
    420      54   156236     187296     194.78   5056   9 chrome
    279      55   174848     176724      48.19   5624   9 chrome
    460      56   164316     182924     104.59   6224   9 chrome
    319      36    95716      99716      26.48   8692   9 chrome
    563      41   252896     251396     445.02  12104   9 chrome
    444      56   193576     222024   1,357.28  12156   9 chrome
    438      55   154580     177040      19.86  17760   9 chrome
   2223      73    45192     113804      48.63   7628   9 explorer
    834      85   232872     188256   1,123.73   3952   0 MsMpEng
   1401      97   151420     198412     138.58   9768   9 PaintDotNet
   1328      88   234760     279732     293.44  11016   9 powershell_ise
    994      62    45524      98704       0.86  18308   9 SearchUI


Executing & Terminating Processes

Start-Process
Let’s first learn how to launch a process from PowerShell. If we want to do anything interesting with our executing process we need use the -passthru argument so that the process id is pass back to our script. 

# Execute notepad and print the process id (PID)
$app = Start-Process notepad -passthru
echo $app.Id

# Launch 5 instances of notepad and keep track of the PIDs
$procs = @{}
1..5 | % { Start-Process notepad -passthru | ForEach-Object { $procs[$_.Id] = $_ }}
echo $procs
Stop-Process
Next, lets review how Stop-Process works 

#Kill process by id
Stop-Process 19320

#Kill process by name
Stop-Process -processname notepad

#Kill process using wildcard search
Stop-Process -processname  note*

#Force termnation a process that is not responding
Stop-Process -processname notepad -Force

Combining Get-Process and Stop-Process

# Passing a Get-Process returned object to Stop-Process
$p = Get-Process notepad
Stop-Process $p

# Same as above but combined into one line
Get-Process notepad | Stop-Process
Terminate the most recent instance of an application
Get-Process notepad | Sort-Object StartTime -Descending | Select-Object Id,Name,StartTime | Select -First 1 | Stop-Process

#Same command expanded for readability
Get-Process notepad `
  | Sort-Object StartTime -Descending `
  | Select-Object Id,Name,StartTime `
  | Select -First 1 `
  | Stop-Process
Terminate the oldest instance of an application
Get-Process notepad | Sort-Object StartTime | Select-Object Id,Name,StartTime | Select -First 1 | Stop-Process

#Same command expanded for readability
Get-Process notepad `
  | Sort-Object StartTime `
  | Select-Object Id,Name,StartTime `
  | Select -First 1 `
  | Stop-Process

Terminate application instances in order, oldest to newest

In this example we also introduce a 2 second delay between each call to Stop-Process. 

# Terminal all instances of an application oldest to newest
# Introducing a delay of 2 seconds between each termination
Foreach( $p in Get-Process notepad | Sort-Object StartTime )
{
    echo "Terminating $($p.Id)"
    Stop-Process $p
    echo "2 Second Delay"
    Start-Sleep -s 2
}

# Script Output

Terminating 4824
2 Second Delay
Terminating 8416
2 Second Delay
Terminating 16460
2 Second Delay
Terminating 10300
2 Second Delay
Terminating 10040
2 Second Delay
#
Start and Stop an Application
# Launch Notepad, wait 5 seconds and close it
$app = Start-Process notepad -passthru
echo $app.Id
Start-Sleep -s 5
Stop-Process $app.Id
Start a process and wait for it to terminate
# Launch notepad and pause script until user closes it
$app = Start-Process notepad -passthru
echo "Notepad Launched"
Wait-Process $app.Id
echo "Notepad Closed"

Launch an application and count how long it was running for

$StartTime = Get-Date
# Launch Notepad
$app = Start-Process notepad -passthru
echo "Notepad Launched"
# Wait for user to close application
Wait-Process $app.Id
echo "Notepad Closed"
$EndTime = Get-Date
echo "Notepad was running for $(($EndTime - $StartTime).Seconds) seconds"

# Script Output
Notepad Launched
Notepad Closed
Notepad was running for 17 seconds
#

Executing & Terminating Multiple Processes

#Start 10 instances of notepad, wait 5 seconds, and then terminate each instance
$procs = New-Object System.Collections.ArrayList
1..10 | % { Start-Process notepad -passthru | ForEach-Object { $procs.Add($_) | Out-Null }}
Start-Sleep -s 5
Foreach($p in $procs) 
{
  echo $p.Id
  Stop-Process $p
}

I hope you have enjoyed this deep dive into the Get-Process command. If you have any suggestions or additions to this article please leave a comment down below.

Get-Process Properties Reference

PS C:\> Get-Process | Get-Member -MemberType Properties

   TypeName: System.Diagnostics.Process

Name                       MemberType     Definition                                                                         
----                       ----------     ----------                                                                         
Handles                    AliasProperty  Handles = Handlecount                                                              
Name                       AliasProperty  Name = ProcessName                                                                 
NPM                        AliasProperty  NPM = NonpagedSystemMemorySize64                                                   
PM                         AliasProperty  PM = PagedMemorySize64                                                             
SI                         AliasProperty  SI = SessionId                                                                     
VM                         AliasProperty  VM = VirtualMemorySize64                                                           
WS                         AliasProperty  WS = WorkingSet64                                                                  
__NounName                 NoteProperty   string __NounName=Process                                                          
BasePriority               Property       int BasePriority {get;}                                                            
Container                  Property       System.ComponentModel.IContainer Container {get;}                                  
EnableRaisingEvents        Property       bool EnableRaisingEvents {get;set;}                                                
ExitCode                   Property       int ExitCode {get;}                                                                
ExitTime                   Property       datetime ExitTime {get;}                                                           
Handle                     Property       System.IntPtr Handle {get;}                                                        
HandleCount                Property       int HandleCount {get;}                                                             
HasExited                  Property       bool HasExited {get;}                                                              
Id                         Property       int Id {get;}                                                                      
MachineName                Property       string MachineName {get;}                                                          
MainModule                 Property       System.Diagnostics.ProcessModule MainModule {get;}                                 
MainWindowHandle           Property       System.IntPtr MainWindowHandle {get;}                                              
MainWindowTitle            Property       string MainWindowTitle {get;}                                                      
MaxWorkingSet              Property       System.IntPtr MaxWorkingSet {get;set;}                                             
MinWorkingSet              Property       System.IntPtr MinWorkingSet {get;set;}                                             
Modules                    Property       System.Diagnostics.ProcessModuleCollection Modules {get;}                          
NonpagedSystemMemorySize   Property       int NonpagedSystemMemorySize {get;}                                                
NonpagedSystemMemorySize64 Property       long NonpagedSystemMemorySize64 {get;}                                             
PagedMemorySize            Property       int PagedMemorySize {get;}                                                         
PagedMemorySize64          Property       long PagedMemorySize64 {get;}                                                      
PagedSystemMemorySize      Property       int PagedSystemMemorySize {get;}                                                   
PagedSystemMemorySize64    Property       long PagedSystemMemorySize64 {get;}                                                
PeakPagedMemorySize        Property       int PeakPagedMemorySize {get;}                                                     
PeakPagedMemorySize64      Property       long PeakPagedMemorySize64 {get;}                                                  
PeakVirtualMemorySize      Property       int PeakVirtualMemorySize {get;}                                                   
PeakVirtualMemorySize64    Property       long PeakVirtualMemorySize64 {get;}                                                
PeakWorkingSet             Property       int PeakWorkingSet {get;}                                                          
PeakWorkingSet64           Property       long PeakWorkingSet64 {get;}                                                       
PriorityBoostEnabled       Property       bool PriorityBoostEnabled {get;set;}                                               
PriorityClass              Property       System.Diagnostics.ProcessPriorityClass PriorityClass {get;set;}                   
PrivateMemorySize          Property       int PrivateMemorySize {get;}                                                       
PrivateMemorySize64        Property       long PrivateMemorySize64 {get;}                                                    
PrivilegedProcessorTime    Property       timespan PrivilegedProcessorTime {get;}                                            
ProcessName                Property       string ProcessName {get;}                                                          
ProcessorAffinity          Property       System.IntPtr ProcessorAffinity {get;set;}                                         
Responding                 Property       bool Responding {get;}                                                             
SafeHandle                 Property       Microsoft.Win32.SafeHandles.SafeProcessHandle SafeHandle {get;}                    
SessionId                  Property       int SessionId {get;}                                                               
Site                       Property       System.ComponentModel.ISite Site {get;set;}                                        
StandardError              Property       System.IO.StreamReader StandardError {get;}                                        
StandardInput              Property       System.IO.StreamWriter StandardInput {get;}                                        
StandardOutput             Property       System.IO.StreamReader StandardOutput {get;}                                       
StartInfo                  Property       System.Diagnostics.ProcessStartInfo StartInfo {get;set;}                           
StartTime                  Property       datetime StartTime {get;}                                                          
SynchronizingObject        Property       System.ComponentModel.ISynchronizeInvoke SynchronizingObject {get;set;}            
Threads                    Property       System.Diagnostics.ProcessThreadCollection Threads {get;}                          
TotalProcessorTime         Property       timespan TotalProcessorTime {get;}                                                 
UserProcessorTime          Property       timespan UserProcessorTime {get;}                                                  
VirtualMemorySize          Property       int VirtualMemorySize {get;}                                                       
VirtualMemorySize64        Property       long VirtualMemorySize64 {get;}                                                    
WorkingSet                 Property       int WorkingSet {get;}                                                              
WorkingSet64               Property       long WorkingSet64 {get;}                                                           
Company                    ScriptProperty System.Object Company {get=$this.Mainmodule.FileVersionInfo.CompanyName;}          
CPU                        ScriptProperty System.Object CPU {get=$this.TotalProcessorTime.TotalSeconds;}                     
Description                ScriptProperty System.Object Description {get=$this.Mainmodule.FileVersionInfo.FileDescription;}  
FileVersion                ScriptProperty System.Object FileVersion {get=$this.Mainmodule.FileVersionInfo.FileVersion;}      
Path                       ScriptProperty System.Object Path {get=$this.Mainmodule.FileName;}                                
Product                    ScriptProperty System.Object Product {get=$this.Mainmodule.FileVersionInfo.ProductName;}          
ProductVersion             ScriptProperty System.Object ProductVersion {get=$this.Mainmodule.FileVersionInfo.ProductVersion;}

Reference

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.