Last active
April 7, 2025 18:39
-
-
Save jhickson/40d7bdfa5b1adba5dff2008d70a24dda to your computer and use it in GitHub Desktop.
Kill all child processes of current Powershell script/session
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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
Errors from
Stop-Process
are ignored in case the process has exited between the query and the call toStop-Process
.