使用VBScript在超时后终止进程

时间:2016-05-25 13:41:55

标签: vbscript

我想检查一下这个过程是否已经运行很长时间(例如5分钟),如果是这样的话就会终止。

下面是我编写的脚本,但它抛出了无效的属性/方法错误:

Const MAX_TIME = 300 'seconds
const I = 1
arrTargetProcs = Array("example.exe")
'process names without extension
do while I = 1
strComputer = "."

Set objWMIService = GetObject("winmgmts:\\" & strComputer)

For Each strTargetProc In arrTargetProcs
  Set colProcesses = objWMIService.ExecQuery _
   ("SELECT * FROM Win32_PerfRawData_PerfProc_Process WHERE Name = '" & _
    strTargetProc & "'")
  If colProcesses.Count > 0 Then
    For Each objProcess In colProcesses
      intProcDur = (objProcess.Timestamp_Object - _
       objProcess.ElapsedTime) / objProcess.Frequency_Object
      If Int(intProcDur) > MAX_TIME Then
        'WScript.Echo "Process " & objProcess.Name & " " & _
         'objProcess.IDProcess & " over time limit."
        Set objProc = objWMIService.Get _
         ("Win32_Process.Handle='" & objProcess.IDProcess & "'")
        intReturn = objProc.Terminate()
        If intReturn = 0 Then
          'WScript.Echo "  Process terminated."
        Else
          'WScript.Echo "  Unable to terminate process."
        End If
      Else
        'WScript.Echo "Process " & objProcess.Name & " " & _
        'objProcess.IDProcess & " not over time limit."
      End If
    Next
  Else
    'WScript.Echo "Process " & strTargetProc & " not found."
  End If
Next
WScript.Sleep 50000
Loop

我收到以下错误:
对象不支持此属性或方法:' objProcess.Timestamp_Object'

我有没有办法确定这个过程是否已经运行了5分钟?

1 个答案:

答案 0 :(得分:0)

检查objProcess.CreationDate值并与Now进行DateDiff通话,其中秒数> 300,调用Terminate方法?

编辑:道歉,以为你引用了Win32_Process对象。对于Win32_PerfRawData_PerfProc_Process,您需要的相关属性为ElapsedTime,根据MSDN,它会提供进程运行的秒数。如果此值超过300,则该过程已运行5分钟或更长时间。

intProcDur = objProcess.ElapsedTime应将intProcDur设置为比较的相关值

编辑2:代码的以下修改版本检索自进程启动以来的秒数(在我的情况下为vbsedit.exe):

arrTargetProcs = Array("Vbsedit.exe")
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer)

For Each strTargetProc In arrTargetProcs
    Set colProcesses = objWMIService.ExecQuery("SELECT * FROM Win32_Process WHERE Name = '" & strTargetProc & "'")
    If colProcesses.Count > 0 Then
        For Each objProcess In colProcesses
            intProcDur = objProcess.CreationDate
            intProcDur = CDate(Mid(intProcDur, 7,2) & "/" & Mid(intProcDur, 5, 2) & "/" & Left(intProcDur,4) & " " & Mid(intProcDur,9,2) & ":" & Mid(intProcDur, 11,2) & ":" & Mid(intProcDur,13,2))

            WScript.Echo objProcess.Name & ": " & intProcDur
            WScript.Echo DateDiff("s", intProcDur, Now) & " seconds since this process began."
        Next
    End If
Next