Search code examples
vbscriptwmi

Killing processes in Vbscript


I am trying to kill all instances of a process called "AetherBS.exe" but the following VBscript is not working. I am not exactly sure where/why this is failing.

So how can I kill all process of "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

Solution

  • The problem is in the following line:

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

    Here you convert the Win32_Process.Name property value to uppercase, but don't convert the Appname to uppercase. By default, InStr performs a case-sensitive search, so if the input strings are the same but differ in case, you won't get a match.

    To fix the problem, you can convert Appname to uppercase as well:

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

    or you can use the vbTextCompare parameter to ignore the letter case:

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


    However, there's actually no need in this check at all as you can incorporate it directly in your query:

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