Determine the number of processes running under the same name

Any ideas on how to write a function that returns the number of process instances are running?

Perhaps something like this?

function numInstances([string]$process) { $i = 0 while(<we can get a new process with name $process>) { $i++ } return $i } 

Edit: started writing a function ... It works for one instance, but it goes into an infinite loop if more than one instance works:

 function numInstances([string]$process) { $i = 0 $ids = @() while(((get-process $process) | where {$ids -notcontains $_.ID}) -ne $null) { $ids += (get-process $process).ID $i++ } return $i } 
+6
source share
4 answers
 function numInstances([string]$process) { @(get-process -ea silentlycontinue $process).count } 

EDIT : added silence and array to work with zero and one process.

+8
source

This works for me:

 function numInstances([string]$process) { @(Get-Process $process -ErrorAction 0).Count } # 0 numInstances notepad # 1 Start-Process notepad numInstances notepad # many Start-Process notepad numInstances notepad 

Conclusion:

 0 1 2 

Although there are just two important points in this solution: 1) use -ErrorAction 0 (0 is the same as SilentlyContinue ), so it works well when there are no specific processes; 2) use the @() array operator to make it work when there is one process instance.

+9
source

Its much easier to use the built-in group cmdlet object:

  get-process | Group-Object -Property ProcessName 
+5
source

There is a nice single line layer: (ps).count

+1
source

Source: https://habr.com/ru/post/892311/


All Articles