Tuesday, December 4, 2007

VBScript: Monitor Processes and Restart if Necessary

VBScript: Monitor Processes and Restart if Necessary

This may only be useful for wscript.exe so it may not have universal appeal but I'll list it anyway. The first script is to be inserted at the top of the wscript file you'd like to monitor. The second file is to be run as a scheduled task. SQL Server is used to keep track of the PIDs. SQL Server Express is free so you have no excuses! ;)
Download Code to find PID

' Author: Chrissy LeMaire
' Copyright 2003 NetNerds Consulting Group
' Script is provided AS IS with no warranties or guarantees and assumes no liabilities.
' Website: http://www.netnerds.net
'create table WscriptPID (PID int,timestamp smalldatetime default getdate())
'''''''''''''''''''''''''''''''''''''''''''''''''''''
'        GET PID FOR MONITORING
'''''''''''''''''''''''''''''''''''''''''''''''''''''
Set objWMIService = GetObject("winmgmts:.
ootcimv2")
strWQL = "Select * from Win32_Process where name = 'wscript.exe'"
Set colProcesses = objWMIService.ExecQuery(strWQL)
    For Each objProcess in colProcesses
        If objProcess.ProcessID > MaxPID Then MaxPID = objProcess.ProcessID 'No MAX in WQL :(
    Next
Set colProcesses = Nothing
Set objWMIService = Nothing
Set Conn = CreateObject("adodb.connection")
    Conn.Open ConnString
        strSQL = "insert into WscriptPID (PID) values (" & MaxPID & ")"
        Conn.execute strSQL
    Conn.Close
Set Conn = Nothing

Download Code for monitoring

' Author: Chrissy LeMaire
' Copyright 2003 NetNerds Consulting Group
' Script is provided AS IS with no warranties or guarantees and assumes no liabilities.
' Website: http://www.netnerds.net
'create table WscriptPID (PID int,timestamp smalldatetime default getdate())
ConnString = "Provider=SQLOLEDB; Data Source=LELAND; Initial catalog=WindowsEvents; Trusted_Connection=yes;"
strComputer = "LELAND" 'Enter your monitoring server name
        Set rs = CreateObject("adodb.recordset")
                strSQL = "select top 1 PID from WscriptPID order by timestamp desc"
                rs.Open strSQL,ConnString,1,1
                    PID = rs("PID")
                rs.Close
            Set rs = Nothing
Set objWMIService = GetObject("winmgmts:.
ootcimv2")
Set colProcesses = objWMIService.ExecQuery("Select * from Win32_Process where ProcessID = " & PID)
    If colProcesses.Count = 0 Then
        Set objWMIProcess = GetObject("winmgmts:" & strComputer & "
ootcimv2:Win32_Process")
            errReturn = objWMIProcess.Create ("wscript.exe C:scriptspush2servers.vbs", Null, Null, intProcessID)
        Set objWMIProcess = Nothing
    End If
Set colProcesses = Nothing
Set objWMIService = Nothing