IGGt
IGGt

Reputation: 2779

powershell v2 - how to get process ID

I have an Application, that runs multiple instances of itself. e.g

AppName.exe instance1
AppName.exe instance2
AppName.exe instance3

Using Powershell v2 I am trying to create a simple script that given an array of AppNames and instances, it loops through them, checks if they are running, and then shuts them down.

I figured the best way to do this would be check for each instance, if found capture it's processID, and pass that to the stop-process cmdlet.

BUT, I can't figure out how to get the process id.

So far I have:

$appName = "AppName.exe"
$instance = "instance1"

$filter = "name like '%"+$appName+"%'"
$result = Get-WmiObject win32_process -Filter $filter

foreach($process in $result )
    {
        $desc = $process.Description
        $commArr = $process.CommandLine -split"( )" 
        $inst = $commArr[2] 
        $procID = "GET PROCESS ID HERE"

        if($inst -eq $instance)
            {
                Stop-Process $procID
            }
    }

Can anyone tell me where to get the process ID from please?

Upvotes: 9

Views: 60380

Answers (3)

BuvinJ
BuvinJ

Reputation: 11096

When using Get-WmiObject win32_process ..., the objects returned have an attribute named ProcessId.

So, in the question, where you have:

$procID = "GET PROCESS ID HERE"

use:

$procID = $process.ProcessId

You could also use that in the $filter assignment, e.g.

$filter = "ProcessId=1234"

Upvotes: 0

omar
omar

Reputation: 81

$procid=(get-process appname).id

Upvotes: 7

Loïc MICHEL
Loïc MICHEL

Reputation: 26170

you can use the get-process cmdlet instead of using wmi :

$procid=get-process appname |select -expand id

Upvotes: 23

Related Questions