Terminate process tree in PowerShell given a process ID
Lets say I run a couple of processes from PowerShell:
$p1 = $(Start-Process -PassThru ./example.exe)
$p2 = $(Start-Process -PassThru ./example.exe)
example.exe
is going to spawn a few child processes with the same name.
How do I kill just $p1
and its child processes, without killing $p2
and its child processes?
Just running Stop-Process $p1
only kills the parent process $p1
, leaving it's children running.
All of the answers I seen so far involve killing all of the processes with a certain name, but that will not work here.
Solution 1:
So I couldn't really find a good way to do this, so I wrote a helper function that uses recursion to walk down the process tree:
function Kill-Tree {
Param([int]$ppid)
Get-CimInstance Win32_Process | Where-Object { $_.ParentProcessId -eq $ppid } | ForEach-Object { Kill-Tree $_.ProcessId }
Stop-Process -Id $ppid
}
To use it, put it somewhere in your PowerShell script, and then just call it like so:
Kill-Tree <process_id>