Skip to content

Instantly share code, notes, and snippets.

@jhickson
Last active December 29, 2018 13:50
Show Gist options
  • Save jhickson/40d7bdfa5b1adba5dff2008d70a24dda to your computer and use it in GitHub Desktop.
Save jhickson/40d7bdfa5b1adba5dff2008d70a24dda to your computer and use it in GitHub Desktop.
Kill all child processes of current Powershell script/session
function KillChildren
{
Param(
[Parameter(Mandatory=$True,Position=1)]
[int]$parentProcessId
)
Get-WmiObject win32_process | where {$_.ParentProcessId -eq $parentProcessId} | ForEach { KillChildren $_.ProcessId }
Get-WmiObject win32_process | where {$_.ParentProcessId -eq $parentProcessId} | ForEach { Stop-Process $_.ProcessId 2>$null }
}
KillChildren $pid
@jhickson
Copy link
Author

Errors from Stop-Process are ignored in case the process has exited between the query and the call to Stop-Process.

@jhickson
Copy link
Author

This could be caught out by a child process that keeps spawning new child.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment