简体   繁体   中英

Kill all processes with a certain name

I have an HTA that runs a backup routine. For the backup I'm using the SyncToy command line executable, which in some instances does not properly cease.

Beacuse of this, I'm trying to kill any process with the name SyncToyCmd.exe . I make use of the window_onBeforeUnload event and call the KillSyncToy() sub from there.

The function is correctly detecting instances of the SyncToyCmd.exe , however when trying to kill the process I'm receiving an error -

Error: The system cannot find the file specified.

I'm guessing that I'm doing something wrong here and any assistance would be welcome.

Sub KillSyncToy()
    Dim WMIService : Set WMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\.\root\cimv2")
    Dim ProcessList : Set ProcessList = WMIService.ExecQuery("SELECT * FROM Win32_Process WHERE Name = 'SyncToyCmd.exe'")

    Dim Process
    For Each Process in ProcessList
        '** Note that 'Shell' is a global instace of the 'WScript.Shell' object, so
        'there is no need to declare it here *'
        Shell.Exec "PSKill " & Process.ProcessId
    Next

    Set WMIService = Nothing
    Set ProcessList = Nothing
End Sub

The error message means that Exec can't find pskill.exe , so the executable most likely isn't located in the %PATH% or the current working directory. You could mitigate that by specifying the full path to the executable.

However, the objects returned from querying Win32_Process have a Terminate method. I'd recommend using that instead of shelling out:

For Each Process in ProcessList
    Process.Terminate
Next

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM