Closing open processes (except excluded) via VBScript

Viewed 195

Currently I use the below portion of VBScript to close running processes, and it works great. But the management issue is that if there's an unknown process, the script isn't going to close it. So I'd like to change this to where all running processes are terminated, unless they're specifically excluded (as there are a few processes that I do not want terminated).

Dim WshShell, objShell 
Set WshShell =  CreateObject("WScript.Shell")

AppList = "iexplore.exe,notepad.exe,wordpad.exe"

'Closing all open applications that are specified in AppList
For Each app In Split(appList, ",")
    Set objProcs=GetObject("winmgmts:\\.\root\cimv2").ExecQuery("select * from Win32_Process where Name= '" & app & "'")
    For Each process In objProcs
        On Error Resume Next
        process.Terminate
        On Error Goto 0
    Next
Next

I've looked, but can't seem to find anything. And I'm ok using a PowerShell command (as all PC's will be Win10), as long as the PS command can be run completely inside of this VBS, without having to maintain a separate PS file.

So something like this would acceptable:

objShell.Run("powershell.exe -switch1 -switch2")

But not this:

objShell.Run("powershell.exe c:\scripts\test.ps1")
1 Answers

The idea of killing all processes except those in an exclude list sounds pretty risky to me. Can you really be sure your exclusion list is complete? New processes (that you may want/need) can be added at any time. This might be okay on a special purpose machine, but I wouldn't use this approach on my general purpose PC. Anyhow, here's the script. Use at your own risk.

Note: With KillEnabled set to False, the script just displays the Exe names that would be killed. Change that value to True to go live. Run using CScript (e.g. cscript killx.vbs).

KillEnabled = False
UserExesOnly = True
Exclude = "applicationframehost,backgroundtaskhost,chsime,cmd,conhost,cscript,ctfmon,dllhost,explorer,mshta,runtimebroker,settingsynchost,searchapp,shellexperiencehost,sihost,smartscreen,startmenuexperiencehost,svchost,systemsettings,textinputhost,useroobebroker,video.ui,wscript"
Exclude = LCase(Exclude)
Set oWMI = GetObject("winmgmts:\\.\root\cimv2")
Set oWSH = WScript.CreateObject("WScript.Shell")
If UserExesOnly Then X = " Where SessionID = 1"
Set oProcesses = oWMI.ExecQuery("SELECT * FROM Win32_Process" & X)
For Each oProcess In oProcesses
  Kill = False
  ExeName = LCase(oProcess.Name)
  If InStr(ExeName,".exe") Then
    Kill = True
    For Each Exe In Split(Exclude,",")
      If InStr(ExeName,Exe & ".exe") Then Kill = False
    Next
    If Kill Then
      If KillEnabled Then
        oProcess.Terminate
      Else
        WScript.Echo ExeName
      End If
    End If
  End If
Next
Related