PowerShell Get-Process – Managing Processes - 4sysops
Có thể bạn quan tâm
- Understanding Get-Process output
- Digging deeper into process properties
- Viewing CPU and memory percentages
- How to kill process
- Author
- Recent Posts
- Install Ansible on Windows - Thu, Jul 20 2023
- Use Azure Bastion as a jump host for RDP and SSH - Tue, Apr 18 2023
- Azure Virtual Desktop: Getting started - Fri, Apr 14 2023
If you’re like me, you’re accustomed to using either the built-in Task Manager or the wonderful freeware Process Explorer to investigate running processes. For reference, I show you those tools in the following figure:
Read 4sysops without ads for free![]()
Windows Task Manager at left, Microsoft Process Explorer at right
Most of the time, I want to perform the following process-related tasks:
- View processes by CPU or RAM consumption in descending order.
- Kill stuck or troublesome processes.
By the end of this article, you’ll know how to do the above and more, all from the fast, low-overhead Windows PowerShell console environment.
Understanding Get-Process output
Let’s begin our investigation by understanding the Get-Process cmdlet output. The bad news is that the default output is neither very understandable nor useful at first glance.
PS C:\> Get-Process | Select-Object -First 5 Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 225 16 2608 7800 105 0.22 5512 acrotray 161 18 2948 3140 104 365.52 1524 AppleMobileDeviceS... 81 7 1084 1600 44 0.03 1508 armsvc 208 13 2556 5268 92 1.38 3136 atieclxx 109 6 824 1152 22 0.00 928 atiesrxxThe Windows PowerShell formatting subsystem “decides” which properties we see in the default output, as well as the view. In the above code, we see that we have eight properties shown in Format-Table style. Let me give you the “CliffsNotes” breakdown:
- Handles: The number of process handles that the process opened. A handle is an integer that Windows assigns to processes. For instance, each process thread is typically assigned a handle.
- NPM(K): Non-paged memory the process is using, in kilobytes.
- PM(K): Pageable memory the process is using, in kilobytes.
- WS(K): Process working set, in kilobytes. The value refers to the number of memory pages that the process recently accessed.
- VM(M): Virtual memory the process is using.
- CPU(s): Processor time used on all processors, in seconds (!).
- Id: Process ID.
- ProcessName: Self-explanatory.
My initial confusion here lies in the CPU(s) property, which gives us processor time instead of a percentage. I also would prefer to see the percentage of RAM that each process used instead of those wacky KB values. We’ll get to those points shortly. Read 4sysops without ads for free
Digging deeper into process properties
We can invoke our friendly Get-Member cmdlet to see the full list of .NET properties that Get-Process exposes:
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 VM AliasProperty VM = VirtualMemorySize64 WS AliasProperty WS = WorkingSet64 __NounName NoteProperty System.String __NounName=Process BasePriority Property int BasePriority {get;} Container Property System.ComponentModel.IContainer C... 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 M... MainWindowHandle Property System.IntPtr MainWindowHandle {get;} MainWindowTitle Property string MainWindowTitle {get;} MaxWorkingSet Property System.IntPtr MaxWorkingSet {get;s... MinWorkingSet Property System.IntPtr MinWorkingSet {get;s... Modules Property System.Diagnostics.ProcessModuleCo... NonpagedSysMemSize Property int NonpagedSystemMemorySize {get;} NonpagedSysMemSize64 Property long NonpagedSystemMemorySize64 {g... PagedMemorySize Property int PagedMemorySize {get;} PagedMemorySize64 Property long PagedMemorySize64 {get;} PagedSysMemSize Property int PagedSystemMemorySize {get;} PagedSysMemSize64 Property long PagedSystemMemorySize64 {get;} PeakPagedMemorySize Property int PeakPagedMemorySize {get;} PeakPgdMemSize64 Property long PeakPagedMemorySize64 {get;} PeakVirtMemSize Property int PeakVirtualMemorySize {get;} PeakVirtMemSize64 Property long PeakVirtualMemorySize64 {get;} PeakWorkingSet Property int PeakWorkingSet {get;} PeakWorkingSet64 Property long PeakWorkingSet64 {get;} PriorityBoostEnabld Property bool PriorityBoostEnabled {get;set;} PriorityClass Property System.Diagnostics.ProcessPriority... PrivateMemorySize Property int PrivateMemorySize {get;} PrivateMemorySize64 Property long PrivateMemorySize64 {get;} PrivProcTime Property timespan PrivilegedProcessorTime {... ProcessName Property string ProcessName {get;} ProcessorAffinity Property System.IntPtr ProcessorAffinity {g... Responding Property bool Responding {get;} SessionId Property int SessionId {get;} Site Property System.ComponentModel.ISite Site {... StandardError Property System.IO.StreamReader StandardErr... StandardInput Property System.IO.StreamWriter StandardInp... StandardOutput Property System.IO.StreamReader StandardOut... StartInfo Property System.Diagnostics.ProcessStartInf... StartTime Property datetime StartTime {get;} SynchronizingObject Property System.ComponentModel.ISynchronize... Threads Property System.Diagnostics.ProcessThreadCo... 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.M... CPU ScriptProperty System.Object CPU {get=$this.Total... Description ScriptProperty System.Object Description {get=$th... FileVersion ScriptProperty System.Object FileVersion {get=$th... Path ScriptProperty System.Object Path {get=$this.Main... Product ScriptProperty System.Object Product {get=$this.M... ProductVersion ScriptProperty System.Object ProductVersion {get=...Sorry about all that code output. I could have suppressed it, but I wanted you to see the Process object property list. The MSDN website has detailed descriptions of every process property, but I want to draw your attention to a couple of things in particular.
First of all, check out the first few properties, which clearly reference the default output columns we saw earlier. These are called alias properties; in other words, they are friendly shortcuts that point to another .NET object. You’ll see alias properties referred to as synthetic members because they aren’t “true” .NET Framework objects. Read 4sysops without ads for free
Second, notice that the CPU property is a script property. What does this mean? Let’s look closer:
PS C:\> Get-Process | Get-Member -Name CPU | Format-List * TypeName : System.Diagnostics.Process Name : CPU MemberType : ScriptProperty Definition : System.Object CPU {get=$this.TotalProcessorTime.TotalSeconds;}This property dips into the System.Object .NET namespace and makes a call to the TotalProcessorTime.TotalSeconds() function.
Viewing CPU and memory percentages
As I said earlier, I’d much prefer if my PowerShell output gave me CPU and memory consumption percentages for my processes.
We can go in a number of directions to solve the CPU percentage problem (including using performance counters). However, I chose to adapt the solution my friends at PowerShell.com cooked up. Here’s my Get-CPU function:
function Get-CPU { $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 5 }Let me help you break down the code by line number:
- 1: I thought it made sense to create a function to support code reuse.
- 3-8: This is a hash table that generates the CPU percentage. I’ll leave understanding the math to you. 😉
- 14: I chose to pull back only the top five processes, but your mileage may vary.
Now, I’ll run the function so you can check out the output:
PS C:\> Get-CPU Name CPUPercent Description ---- ---------- ----------- igfxEM 15.77 igfxEM Module vmware-vmx 8.33 VMware Workstation VMX dwm 3.58 Desktop Window Manager vmware-vmx 2.13 VMware Workstation VMX System 1.92Let’s turn our attention to getting RAM consumption percentages. This time, I won’t use a function; I adapted this code from Lee Holmes’s Windows PowerShell Cookbook.
We’ll start by creating a hashtable that gives us a custom column named “Process Name” and converts process working set bytes data into megabytes:
$output = "Name",@{Label = "RAM(MB)"; Expression = {$_.WS / 1MB}; Align = "Right"}Next, we’ll add the $output variable to our Get-Process pipeline:
PS C:\> Get-Process | Sort-Object -Property WorkingSet -Descending | Select-Object -First 5 | Format-Table $output -AutoSize Name RAM(MB) ---- ------- chrome 915.5546875 chrome 573.80859375 chrome 448.58203125 chrome 218.6015625 explorer 203.07421875Man, Google Chrome eats up major memory on my Windows 8.1 system, doesn’t it? You can further tweak the code if, for instance, you want to round your RAM(MB) values to the nearest megabyte.
How to kill process
I’ll bet not two days go by without needing to kill a stuck or otherwise troublesome process, am I correct? We can use the PowerShell pipeline and even cmdlet aliases to take care of this quickly and easily.
A bit of trivia: you can use either kill or Stop-Process to kill processes, thanks to PowerShell’s alias system:
PS C:\> Get-Alias -Definition Stop-Process CommandType Name ----------- ---- Alias kill -> Stop-Process Alias spps -> Stop-ProcessOf course, we need the name of the process we want to stop. Let’s look for the top five processes consuming more than 25MB RAM:
PS C:\> Get-Process | Where-Object { $_.WorkingSet -gt 25000*1024 } | Sort-Object -Property WorkingSet -Descending | Select-Object -First 8 Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 296 110 940592 931592 1834 1,466.11 6160 chrome 283 73 573616 580776 1449 827.08 11752 chrome 2098 87 411932 469412 1288 1,190.36 15040 chrome 203 43 286624 301724 1164 6.28 16980 chrome 297 62 238064 254776 623 40.95 13880 Spotify 232 36 220384 225408 1116 50.70 5388 chrome 791 48 208524 213696 ...66 3.08 2852 powershell 3685 161 114496 206756 ...39 1,458.67 3428 explorerI’m going to kill my Spotify music player and have PowerShell prompt me for confirmation, and we’ll use -PassThru to force PowerShell to show us what object it just acted upon:
Subscribe to 4sysops newsletter!
Stop-Process -Name Spotify -Confirm -PassThru Confirm Are you sure you want to perform this action? Performing the operation "Stop-Process" on target "Spotify (6728)". [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"):y Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 401 44 111316 142004 356 23.08 6728 SpotifyOf course, we can also use PowerShell parameter binding to accomplish the same result, like this:
Get-Process -Name Spotify | Stop-Process 2 Comments Read 4sysops without ads for free
Từ khóa » Npm(k) Pm(k) Ws(k) Vm(m)
-
What Do The Headers In The PowerShell Ps Output Mean? - Super User
-
Get-Process (Microsoft.PowerShell.Management)
-
Managing Processes With Process Cmdlets - PowerShell
-
What It Means When PM(K) Of Ps Gets Negative Values?
-
What It Means When PM(K) Of Ps Gets Negative Values? - Server Fault
-
Khám Phá 10 Tính Năng Của PowerShell
-
How To Monitor The Resources Used By OpenEdge Processes On ...
-
Month Of PowerShell: Process Threat Hunting, Part 1 | SANS Institute
-
Get-Process - PowerShell Command - PDQ
-
Fanfare For The Common Parameter Part 3: Success
-
Q. How Do I Access Attributes Of Objects Piped To Other Expressions?
-
PowerShell Tutorial => Set-Alias
-
PowerShell Get-process Cmdlet - MoonPoint Support
-
1 1.0.0.0 - PowerShell Gallery