Wanted to post this under "Example Scripts" forum but I did not have the permission.
2 days ago I needed to create something like pskill to kill process and all its child process. I searched thru the forums hoping someone already done this but only found left for dead post threads of the subject. So i took a stab at it and this is what I came up with.
Killing Process
;_processKillTree("cmd.exe")
Func _ProcessKillTree($ProcessTreeKill)
local $PID
If Processexists($ProcessTreeKill) Then
$PID = Processexists($ProcessTreeKill)
$oWmiService = ObjGet("winmgmts:\\.\root\CIMV2")
;SQL query requesting for all process that has ProcessID of executable trying to kill
$ChildProc = $oWmiService.Execquery("SELECT ProcessID FROM Win32_Process WHERE ParentProcessId='" & $PID & "'")
If isObj($ChildProc) then
;Suspending process in case it tries to recreate child process
_SuspendExe($PID)
For $Child in $ChildProc
;closing child process
ProcessClose($child.ProcessID)
Next
processclose($PID)
Endif
EndIf
EndFunc
Here's code for the _suspendExe function used in the ProcessKillTree function.
Func _SuspendExe($PID)
Local $THREAD_SUSPEND_RESUME =0x0002
$oWmiService = ObjGet("winmgmts:\\.\root\CIMV2")
$ThreadHandle = $oWmiService.Execquery("SELECT Handle FROM Win32_Thread WHERE ProcessHandle='" & $PID & "'")
if isobj($threadHandle) then
For $TID in $threadHandle
;Getting the handle of thread
$hwnd = DllCall('Kernel32.dll','hwnd',"OpenThread","int",$THREAD_SUSPEND_RESUME,"int",0,'int',$TID.handle)
$ret = DllCall('kernel32.dll','uint',"SuspendThread",'hwnd',$hwnd[0])
next
EndIf
EndFunc
Here's how to resume a thread
Func _ResumeExe($PID)
local $THREAD_SUSPEND_RESUME =0x0002
$oWmiService = ObjGet("winmgmts:\\.\root\CIMV2")
$ThreadHandle = $oWmiService.Execquery("SELECT Handle FROM Win32_Thread WHERE ProcessHandle='" & $PID & "'")
if isobj($threadHandle) then
For $TID in $threadHandle
$hwnd = DllCall('Kernel32.dll','hwnd',"OpenThread","int",$THREAD_SUSPEND_RESUME,"int",0,'int',$TID.handle)
$ret = DllCall('kernel32.dll','uint',"ResumeThread",'hwnd',$hwnd[0])
next
EndIf
EndFunc
I've tested on xp sp2 only so am not sure if it will work with any other flavor of Micro$oft.
Thanks for reading and I hope someone has a use for it.
Any positive suggestions would be appreciated.