Detect number of processes running with the same name

…衆ロ難τιáo~ 提交于 2019-12-03 03:22:01
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
}

# 0
numInstances notepad

# 1
Start-Process notepad
numInstances notepad

# many
Start-Process notepad
numInstances notepad

Output:

0
1
2

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

There is a nice one-liner : (ps).count

(Get-Process | Where-Object {$_.Name -eq 'Chrome'}).count

This will return you the number of processes with same name running. you can add filters to further format your data.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!