Detect number of processes running with the same name
function numInstances([string]$process){ @(get-process -ea silentlycontinue $process).count}
EDIT: added the silently continue and array cast to work with zero and one processes.
This works for me:
function numInstances([string]$process){ @(Get-Process $process -ErrorAction 0).Count}# 0numInstances notepad# 1Start-Process notepadnumInstances notepad# manyStart-Process notepadnumInstances notepad
Output:
012
Though it is simple there are two important points in this solution: 1) use -ErrorAction 0
(0 is the same as SilentlyContinue
), so that it works well when there are no specified processes; 2) use the array operator @()
so that it works when there is a single process instance.
Its much easier to use the built-in cmdlet group-object:
get-process | Group-Object -Property ProcessName