在Vbscript中杀死进程

时间:2010-07-21 14:53:02

标签: vbscript wmi

我正在尝试杀死名为“AetherBS.exe”的进程的所有实例,但以下VBscript无效。我不确定这会失败的地点/原因。

那么如何杀死“AetherBS.exe”的所有进程呢?

CloseAPP "AetherBS.exe"

Function CloseAPP(Appname)
    strComputer = "."
    Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
    Set colItems = objWMIService.ExecQuery( _
        "SELECT * FROM Win32_Process", , 48)
    For Each objItem In colItems
        If InStr(1,Ucase(objItem.Name),Appname) >= 1 Then
            objItem.Terminate
        End If
    Next
End Function

3 个答案:

答案 0 :(得分:8)

这是杀死进程的函数:

Sub KillProc( myProcess )
'Authors: Denis St-Pierre and Rob van der Woude
'Purpose: Kills a process and waits until it is truly dead

    Dim blnRunning, colProcesses, objProcess
    blnRunning = False

    Set colProcesses = GetObject( _
                       "winmgmts:{impersonationLevel=impersonate}" _
                       ).ExecQuery( "Select * From Win32_Process", , 48 )
    For Each objProcess in colProcesses
        If LCase( myProcess ) = LCase( objProcess.Name ) Then
            ' Confirm that the process was actually running
            blnRunning = True
            ' Get exact case for the actual process name
            myProcess  = objProcess.Name
            ' Kill all instances of the process
            objProcess.Terminate()
        End If
    Next

    If blnRunning Then
        ' Wait and make sure the process is terminated.
        ' Routine written by Denis St-Pierre.
        Do Until Not blnRunning
            Set colProcesses = GetObject( _
                               "winmgmts:{impersonationLevel=impersonate}" _
                               ).ExecQuery( "Select * From Win32_Process Where Name = '" _
                             & myProcess & "'" )
            WScript.Sleep 100 'Wait for 100 MilliSeconds
            If colProcesses.Count = 0 Then 'If no more processes are running, exit loop
                blnRunning = False
            End If
        Loop
        ' Display a message
        WScript.Echo myProcess & " was terminated"
    Else
        WScript.Echo "Process """ & myProcess & """ not found"
    End If
End Sub

<强>用法:

KillProc "AetherBS.exe"

答案 1 :(得分:4)

问题出在以下几行:

If InStr(1,Ucase(objItem.Name),Appname) >= 1 Then

这里将Win32_Process.Name属性值转换为大写,但不要将Appname转换为大写。默认情况下,InStr执行区分大小写的搜索,因此如果输入字符串相同但大小写不同,则无法获得匹配。

要解决此问题,您还可以将Appname转换为大写:

If InStr(1, UCase(objItem.Name), UCase(Appname)) >= 1 Then

或者您可以使用vbTextCompare参数忽略字母大小写:

If InStr(1, objItem.Name, Appname, vbTextCompare) >= 1 Then


但是,实际上根本不需要进行此检查,因为您可以直接将其合并到查询中:

Set colItems = objWMIService.ExecQuery( _
    "SELECT * FROM Win32_Process WHERE Name='" & Appname & "'", , 48)

答案 2 :(得分:-1)

使用批处理脚本

尝试下面的内容
wmic path win32_process Where "Caption Like '%%AetherBS.exe%%'" Call Terminate

从命令行使用

wmic path win32_process Where "Caption Like '%AetherBS.exe%'" Call Terminate