Kill process by ParentProcessID

2019-08-05 16:56发布

问题:

I want to kill a running process by its ParentProcessID. I want to do it like you can do it in the commandline:

wmic process where parentprocessid= 3008 terminate 

But now the thing is, in PowerShell I've the ParentProcessID as a variable like this:

$p = 3008

And now I would like to kill the process by the varibale $p but this doesn't work:

wmic process where parentprocessid= $p terminate

How can I kill a process by its ParentProcessID, if I have the ParentProcessID stored in a variable?

回答1:

Retrieve the Win32_Process object with Get-WmiObject and pipe it to Invoke-WmiMethod to invoke the Terminate method:

Get-WmiObject Win32_Process -Filter "ParentProcessId=$p" | Invoke-WmiMethod Terminate


回答2:

Try this:

$parentId = 3008
$name = "Process name"

Get-WmiObject -Class Win32_Process | 
where {$_.ParentProcessId -eq $parentId -and $_.Name -eq $name} | 
foreach {$_.terminate(0)}

Added $name parameter cause there may be several child processes. If you need to kill'em all just skip -and $_.Name -eq $name



回答3:

I found the solution, it was just to remove the space between the "=" and the variable name.

wmic process where parentprocessid=$p terminate