Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terminate process tree in PowerShell given a process ID

Tags:

powershell

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.

like image 372
wheeler Avatar asked Apr 29 '19 03:04

wheeler


1 Answers

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>
like image 163
wheeler Avatar answered Nov 06 '22 06:11

wheeler