我尝试编写VBScript,每5分钟检查一个进程,如果它没有运行则执行它,然后每15分钟就会终止该进程,以便启动一个新实例。我有一个开始部分来检查和启动过程,但我无法让后面的部分工作。这是我到目前为止所拥有的。
Set WshShell = CreateObject("WScript.Shell")
Set service = GetObject ("winmgmts:")
Do Until i=1
bIsRunning = False
For Each Process In service.InstancesOf("Win32_Process")
If Process.Name = "Service.exe" Then
bIsRunning = True
End If
Next
If Not bIsRunning Then
WshShell.Run "C:\Users\Dustin\Programs\Service\Service.exe"
End If
WScript.Sleep 300000
Loop
我试图把这样的东西扔到那里
oShell.Run "taskkill /f /im Service.exe", , True
WScript.Sleep 15000
我如何将两个睡眠参数放入一个脚本?
答案 0 :(得分:2)
处理进程超时的最简单方法可能是检查WMI Process对象的CreationDate
属性,并将进程日期时间与当前日期时间进行比较。
唯一的问题是WMI日期时间与VBScript中常用的VT_DATE不同。但是,我们可以使用WbemScripting.SWbemDateTime
(SWbemDateTime)实例来处理转换。
Option Explicit
' WMI constants
Const wbemFlagForwardOnly = 32
' Process constants.
Const PROCESS_NAME = "service.exe"
CONST PROCESS_COMMANDLINE = "C:\Users\Dustin\Programs\Service\Service.exe"
Const PROCESS_RUNNING_MINUTES = 15
' Monitoring constants
Const SLEEP_TIME = 300000
' Grab a reference to WMI
Dim wmi
Set wmi = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
' Get an instance of a SWBemDateTime object to deal with WMI datetimes
Dim swbemDT
Set swbemDT = WScript.CreateObject("WbemScripting.SWbemDateTime")
Dim bRunning, process, colProcesses
Do While True
' Retrieve the list of matching processes
Set colProcesses = wmi.ExecQuery( _
"SELECT CreationDate From Win32_Process " & _
"WHERE Name='" & PROCESS_NAME & "'" _
,"WQL" , wbemFlagForwardOnly _
)
' Calculate when the process should have been started
swbemDT.SetVarDate DateAdd( "n", (-1 * PROCESS_RUNNING_MINUTES), Now())
' We don't know if there is a valid running instance
bRunning = False
For Each process In colProcesses
' Check if the process is too old or it is a valid running instance
If process.CreationDate < swbemDT Then
' Too old, termite the process
process.Terminate
Else
' We have found a valid running instance
bRunning = True
End If
Next
' If we have not found any valid running instance, start a new process
If Not bRunning Then
WScript.CreateObject("WScript.Shell").Run PROCESS_COMMANDLINE, 0, False
End If
' Wait before a new process check
WScript.Sleep SLEEP_TIME
Loop