【问题标题】:Closing open processes (except excluded) via VBScript通过 VBScript 关闭打开的进程(排除的除外)
【发布时间】:2021-11-17 21:16:02
【问题描述】:

目前我使用 VBScript 的以下部分来关闭正在运行的进程,效果很好。但管理问题是,如果存在未知进程,脚本不会关闭它。因此,我想将其更改为终止所有正在运行的进程的位置,除非它们被明确排除(因为有一些进程我不想终止)。

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

我看过,但似乎找不到任何东西。而且我可以使用 PowerShell 命令(因为所有 PC 都是 Win10),只要 PS 命令可以完全在此 VBS 内运行,无需维护单独的 PS 文件。

所以这样的事情是可以接受的:

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

但不是这个:

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

【问题讨论】:

    标签: vbscript process


    【解决方案1】:

    杀死除排除列表中的所有进程之外的所有进程的想法对我来说听起来很冒险。你真的能确定你的排除清单是完整的吗?可以随时添加新流程(您可能想要/需要)。这在专用机器上可能没问题,但我不会在我的通用 PC 上使用这种方法。无论如何,这是脚本。使用风险自负。

    注意:将 KillEnabled 设置为 False,脚本仅显示将被杀死的 Exe 名称.将该值更改为 True 即可上线。使用 CScript 运行(例如 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
    

    【讨论】:

    • 不,我完全理解您的担忧,因为通常它是有效的。但这是一个特定的用例,因为我很清楚系统可能需要终止进程的问题。尽管您的脚本失败(启用或禁用 Kill)。禁用后,它将回显进程,但随后在第 12 行,字符 26,未找到,80041002,SWbemObjectEx 处失败。有什么想法吗?
    • @Brian 我用 SessionID = 1 上的过滤器替换了对 GetOwner 的调用(间歇性 SWbemObjectEx 错误的来源),以将任务列表缩小到当前用户进程。当然,这是假设一个典型的并发用户情况。此方法快速可靠。
    • 抱歉,现在才开始测试。是的,这似乎有效。尽管我第一次运行它时遇到了错误,尽管我没有截取它的屏幕截图,并且您删除了您之前对我之前遇到的错误的评论。但是从那以后我就没有得到它,我已经重新启动了我的虚拟机几次并重新运行它没有任何问题......也许我不小心双击了一个不同的脚本。我将不得不做更多的测试,但看起来这会奏效。将在更多测试后更新。谢谢!
    猜你喜欢
    • 2015-06-16
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-27
    • 1970-01-01
    • 1970-01-01
    • 2023-01-19
    相关资源
    最近更新 更多