Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect number of processes running with the same name

Any ideas of how to write a function that returns the number of instances of a process is 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 to write a function... It works for a single instance but it goes into an infinite loop if more than one instance is running:

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
}
like image 966
Jack Avatar asked Jul 08 '11 10:07

Jack


4 Answers

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.

like image 64
Matt Avatar answered Sep 28 '22 05:09

Matt


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

like image 22
wwebec Avatar answered Sep 28 '22 03:09

wwebec


(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.

like image 32
ArunAshokan Avatar answered Sep 28 '22 05:09

ArunAshokan


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

 get-process | Group-Object -Property ProcessName
like image 37
Chad Miller Avatar answered Sep 28 '22 05:09

Chad Miller