13

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
}
tshepang
  • 12,111
  • 21
  • 91
  • 136
Jack
  • 2,153
  • 5
  • 28
  • 43

5 Answers5

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

Matt
  • 1,931
  • 12
  • 20
10

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.

Roman Kuzmin
  • 40,627
  • 11
  • 95
  • 117
7

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

 get-process | Group-Object -Property ProcessName
Chad Miller
  • 40,127
  • 3
  • 30
  • 34
5

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

wwebec
  • 51
  • 1
  • 2
3

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

ArunAshokan
  • 55
  • 1
  • 10