Jump to content

kill process by path


Recommended Posts

Hi,

I am trying to write a script that will run when I plug in my USB stick, wait in the background, and then close all the programs that were opened from the stick when I unplug it.

I've gotten the script to work and run fine, but I have to manually specify the programs to close in the script or in a text file. Is there any way to close all programs associated with a drive letter or folder? For example, close all programs with a path reference of G:\Folder\

This is what I have so far:

;=========================================================
;USB Insert
;
;calls process to kill processes on usb drive unplug
;as well as calls portable apps menu.
;
;=========================================================

#NoTrayIcon
FileInstall(".\USB Remove.exe", @TempDir & '\', 1)
Run(".\StartPortableApps.exe", "", @SW_HIDE)
Run(@TempDir & "\USB Remove.exe", "", @SW_HIDE)
Exit

;=========================================================
;USB Remove
;
;Kills processes attached to usb device on unplug
;
;=========================================================
#NoTrayIcon
FileInstall(".\taskkill.exe", @TempDir & '\', 1)
;$path = ("G:\PortableApps\")
$strComputer = "."
$objWMIService = ObjGet("winmgmts:\\" & $strComputer & "\root\cimv2")

$colEvents = $objWMIService.ExecNotificationQuery _
        ("Select * From __InstanceOperationEvent Within 5 Where " _
         & "TargetInstance isa 'Win32_LogicalDisk'")


While 1
    $objEvent = $colEvents.NextEvent
    If $objEvent.TargetInstance.DriveType = 2 Then
        
        If $objEvent.Path_.Class () = "__InstanceDeletionEvent" Then
        ;Run(@TempDir & "\Kill.exe killbypath " & $path & "PortableAppsMenu\PortableAppsMenu.exe", "", @SW_HIDE)
            Run(@TempDir & "\taskkill.exe /F /IM PortableAppsMenu.exe", "", @SW_HIDE)
            Run(@TempDir & "\taskkill.exe /F /IM gaim.exe", "", @SW_HIDE)
            Run(@TempDir & "\taskkill.exe /F /IM skype.exe", "", @SW_HIDE)
            _RefreshSystemTray()
            ExitLoop
        EndIf
    EndIf
WEnd


; ===================================================================
; _RefreshSystemTray($nDealy = 1000)
;
; Removes any dead icons from the notification area.
; Parameters:
;   $nDelay - IN/OPTIONAL - The delay to wait for the notification area to expand with Windows XP's
;       "Hide Inactive Icons" feature (In milliseconds).
; Returns:
;   Sets @error on failure:
;       1 - Tray couldn't be found.
;       2 - DllCall error.
; ===================================================================
Func _RefreshSystemTray($nDelay = 1000)
; Save Opt settings
    Local $oldMatchMode = Opt("WinTitleMatchMode", 4)
    Local $oldChildMode = Opt("WinSearchChildren", 1)
    Local $error = 0
    Do; Pseudo loop
        Local $hWnd = WinGetHandle("classname=TrayNotifyWnd")
        If @error Then
            $error = 1
            ExitLoop
        EndIf

        Local $hControl = ControlGetHandle($hWnd, "", "Button1")

    ; We're on XP and the Hide Inactive Icons button is there, so expand it
        If $hControl <> "" And ControlCommand($hWnd, "", $hControl, "IsVisible") Then
            ControlClick($hWnd, "", $hControl)
            Sleep($nDelay)
        EndIf

        Local $posStart = MouseGetPos()
        Local $posWin = WinGetPos($hWnd)

        Local $y = $posWin[1]
        While $y < $posWin[3] + $posWin[1]
            Local $x = $posWin[0]
            While $x < $posWin[2] + $posWin[0]
                DllCall("user32.dll", "int", "SetCursorPos", "int", $x, "int", $y)
                If @error Then
                    $error = 2
                    ExitLoop 3; Jump out of While/While/Do
                EndIf
                $x = $x + 8
            WEnd
            $y = $y + 8
        WEnd
        DllCall("user32.dll", "int", "SetCursorPos", "int", $posStart[0], "int", $posStart[1])
    ; We're on XP so we need to hide the inactive icons again.
        If $hControl <> "" And ControlCommand($hWnd, "", $hControl, "IsVisible") Then
            ControlClick($hWnd, "", $hControl)
        EndIf
    Until 1

; Restore Opt settings
    Opt("WinTitleMatchMode", $oldMatchMode)
    Opt("WinSearchChildren", $oldChildMode)
    SetError($error)
EndFunc  ;==>_RefreshSystemTray
Link to comment
Share on other sites

Try this, it will look for all .exe's in a given folder and close them.

Func _KillProcessesByFolder($folder)
    Local $fo = FileFindFirstFile($folder & "*.exe")
    While @error <> 1
        $pro = FileFindNextFile($fo)
        If @error = 1 Then
            FileClose($fo)
            Return 1
        EndIf
        If ProcessExists($pro) Then ProcessClose($pro)
    WEnd
    FileClose($fo)
EndFunc

_KillProcessesByFolder("C:\")
Link to comment
Share on other sites

Try this, it will look for all .exe's in a given folder and close them.

Func _KillProcessesByFolder($folder)
    Local $fo = FileFindFirstFile($folder & "*.exe")
    While @error <> 1
        $pro = FileFindNextFile($fo)
        If @error = 1 Then
            FileClose($fo)
            Return 1
        EndIf
        If ProcessExists($pro) Then ProcessClose($pro)
    WEnd
    FileClose($fo)
EndFunc

_KillProcessesByFolder("C:\")
Ok, I tried that, but when i run the script the usb drive is already unplugged. Instead I've come up with this:

While 1
    $objEvent = $colEvents.NextEvent
    If $objEvent.TargetInstance.DriveType = 2 Then
        If $objEvent.Path_.Class () = "__InstanceDeletionEvent" Then
            RunWait(@ComSpec & " /c kill.exe list g:\ > C:\Process.txt", "", @SW_HIDE)
            $file = ('c:\process.txt')
            $sRead = FileRead($file)
            $proc = StringRegExp($sRead, '[0-9]+', 3)
            For $iCC = 0 To UBound($proc) - 1
                RunWait(@ComSpec & " /c kill.exe " & $proc[$iCC], "", @SW_HIDE)
            Next
            _RefreshSystemTray()
        ;Cleanup
            FileClose($file)
            FileDelete($file)
            ExitLoop
        EndIf
    EndIf
WEnd

I needed to be able to find the path / process Id from running programs while the drive was unplugged and kill.exe does this.

http://www.mayabase.nl/index.php?PageID=29

I will probably end up moving the temp file to a temp dir, and haveing part of the script give the drive a specific letter no matter what machine it is plugged into. But for now it's looking good :shocked:

Link to comment
Share on other sites

Would this be what you mean?

I saw this example quite some time ago, don't remember where so I'm sorry but I can't give credits. Did change it some. Also there is a brilliant system info UDF on this forum somewhere, which contains functions to get this kind of stuff and LOTS of other process and system information functions...

Hope this helps.

Cheers!

#include <Array.au3>

Global $wbemFlagReturnImmediately = 0x10, _ ;DO NOT CHANGE
        $wbemFlagForwardOnly = 0x20     ;DO NOT CHANGE

Local $colItems, $objWMIService, $objItem
Local $expath = ""

$objWMIService = ObjGet("winmgmts:\\" & @ComputerName & "\root\CIMV2")
$colItems = $objWMIService.ExecQuery ("SELECT * FROM Win32_Process", "WQL", $wbemFlagReturnImmediately + $wbemFlagForwardOnly)

Dim $expath[1]

If IsObj($colItems) Then
    For $objItem In $colItems
        ReDim $expath[UBound($expath)+1]
        $expath[UBound($expath)-1] = $objItem.ExecutablePath
    Next
EndIf

_ArrayDisplay($expath,"Executable Paths")

Roses are FF0000, violets are 0000FF... All my base are belong to you.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...