2010-07-21 250 views
0

我試圖殺死一個名爲「AetherBS.exe」的進程的所有實例,但是下面的VBScript不起作用。我不完全確定這是失敗的原因。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 
+0

你得到一個錯誤?如果是,那麼哪個錯誤和哪一行?另外,你在使用什麼操作系統? – Helen 2010-07-21 15:00:11

+0

沒有錯誤和Windows Server 2003. – 2010-07-21 15:05:25

回答

3

問題出在下面一行:

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) 
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" 
+0

成功地終止了該進程。有沒有一種方法可以在沒有Windows Script Host消息框提示的情況下終止進程? 我正在嘗試自動化測試,並且提示正在有效地停止腳本。 – 2010-07-21 15:04:52

+0

@iobrien:簡單地刪除它所說的「WScript.Echo」。 – Sarfraz 2010-07-21 15:15:24

-1

嘗試下面用批處理腳本

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

從CMD線使用

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