VB Scripts for Windows Server Monitoring

Various VB Scripts for Server Monitoring :

1) IIS Status

Set colOperatingSystems = objWMIService.ExecQuery _
("Select * from Win32_OperatingSystem")

For Each objOperatingSystem In colOperatingSystems

 OSVer= objOperatingSystem.Caption

 If InStr(1,OSVer,"2008") > 0 Then
  
  objFile.WriteLine OSVer
  
  WinSevIISFn()
  
 Else 
  WinThrIISFn() 'create win 2003 server function 
 End If 

Next

Function WinSevIISFn()

 IISbatpath   = objFSO.GetParentFolderName(WScript.ScriptFullName) & "\IISState.bat"

 objShell.run IISbatpath

 WScript.sleep(1000)

 webstpath      = objFSO.GetParentFolderName(WScript.ScriptFullName) & "\Websitestate.txt"
 Appplstpath    = objFSO.GetParentFolderName(WScript.ScriptFullName) & "\AppPoolsstate.txt"

 objIISwebState = objFSO.OpenTextFile(webstpath, ForReading).ReadAll

 objIISAppState = objFSO.OpenTextFile(Appplstpath, ForReading).ReadAll

 IISWebarrLines = Split(objIISwebState, vbCrLf)

 For Each strIISweb In IISWebarrLines
  
  If Len(strIISweb) > 0 Then
   
   websiteName = Mid(strIISweb,7, InStr(8,strIISweb,Chr(34))-7 )
  End If
  
  If InStr(1,strIISweb,"state:Started") > 0 Then
   
   objFile.WriteLine "Web site :" & websiteName & " is Running"
   
  ElseIf InStr(1,strIISweb,"state:Stopped") > 0 Then
   
   objFile.WriteLine "Web site:"& websiteName  & " is Stopped,"
   
   WebsiteStart(websiteName)
   
  End If
 Next

 IISAPParrLines = Split(objIISAppState, vbCrLf)

 For Each strIISAppl In IISAPParrLines
  
  If Len(strIISAppl) > 0 Then
   
   AppPlNm= Mid(strIISAppl,10, InStr(10,strIISAppl,Chr(34))-10 )
  End If
  
  If InStr(1,strIISAppl,"state:Started") > 0 Then
   
   objFile.WriteLine "App Pool: " & AppPlNm & " is Running."
   
  ElseIf InStr(1,strIISAppl,"state:Stopped") > 0 Then
   
   AppPlStrt(AppPlNm)
   
   objFile.WriteLine AppPlNm & " is Stopped."
   
  End If
 Next
 Set objShell=Nothing
 End Function

 '################

function CnfrmIISRstrtSvn(argAppl,argwbsite)
  
  IISbatpath   = objFSO.GetParentFolderName(WScript.ScriptFullName) & "\IISState.bat"
  
  objShell.run IISbatpath
  
  WScript.sleep(1000)
  
  webstpath      = objFSO.GetParentFolderName(WScript.ScriptFullName) & "\Websitestate.txt"
  Appplstpath    = objFSO.GetParentFolderName(WScript.ScriptFullName) & "\AppPoolsstate.txt"
  
  objIISwebState = objFSO.OpenTextFile(webstpath, ForReading).ReadAll
  
  objIISAppState = objFSO.OpenTextFile(Appplstpath, ForReading).ReadAll
  
  IISWebarrLines = Split(objIISwebState, vbCrLf)
  
  For Each strIISweb In IISWebarrLines
   
   If Len(strIISweb) > 0 Then
    
    websiteName = Mid(strIISweb,7, InStr(8,strIISweb,Chr(34))-7 )
   End If
   
   If InStr(1,strIISweb,"state:Started") > 0 Then
    
    WbsiteSts = "STARTED"
    
   ElseIf InStr(1,strIISweb,"state:Stopped") > 0 Then
    
    WbsiteSts= "STOPPED"
    
   End If
   
  Next
  argwbsite = WbsiteSts
  
  IISAPParrLines = Split(objIISAppState, vbCrLf)
  
  For Each strIISAppl In IISAPParrLines
   
   If Len(strIISAppl) > 0 Then
    
    AppPlNm= Mid(strIISAppl,10, InStr(10,strIISAppl,Chr(34))-10 )
   End If
   
   If InStr(1,strIISAppl,"state:Started") > 0 Then
    
    Appolsts = "STARTED"
    
   ElseIf InStr(1,strIISAppl,"state:Stopped") > 0 Then
    
    Appolsts = "STOPPED"
    
   End If
   
  Next
  argAppl=Appolsts
  
  Set objShell=Nothing
  
 End FUNCTION

function CnfrmIISRstrtThr(wbstSts)
  
  On Error Resume Next
  Set objWebService = GetObject( "IIS://"& strComputer &"/W3SVC" )
  
  For Each objWebServer In objWebService
   websitestatus= objWebServer.ServerState
   Select Case websitestatus  
    Case 1
    wbstSts ="STARTED"
    Case 2
    wbstSts ="STARTED"
    Case 3
    objFile.WriteLine "Web site:"&  objWebServer.ServerComment & " Is Stopping"
    
    wbstSts ="STOPPED"
    
    Case 4
    wbstSts ="STOPPED"

    
    Case Else
    
    wbstSts ="UNKNOWN"
    
   End Select
  Next
  
 End function

 '################

Function WinThrIISFn()

 Set objWMIService1 = GetObject _
 ("winmgmts:{authenticationLevel=pktPrivacy}\\" _
 & strComputer & "\root\microsoftiisv2")

 Set colItems1 = objWMIService1.ExecQuery _
 ("Select * from IIsApplicationPoolSetting")

 For Each objItem1 In colItems1
  
  Select Case objItem1.AppPoolState
   
   Case 2
   objFile.WriteLine "Application Pool Name:"& objItem1.Name & " Running"
   
   Case 4
   objFile.WriteLine  "Application Pool Name:"& objItem1.Name &  " Down"
  
   IISRestart()
   
  End Select 
  
 Next 

 On Error Resume Next
 Set objWebService = GetObject( "IIS://"& strComputer &"/W3SVC" )

 For Each objWebServer In objWebService
  websitestatus= objWebServer.ServerState
  Select Case websitestatus
   
   Case 1
   objFile.WriteLine "Web site:"&  objWebServer.ServerComment & " Is Running"
   Case 2
   objFile.WriteLine "Web site:"&  objWebServer.ServerComment & " Is Running"
   Case 3
   objFile.WriteLine "Web site:"&  objWebServer.ServerComment & " Is Stopping"
   
   WinThreWebStr objWebServer.ServerComment,objWebServer.Name
   
   Case 4
   
   objFile.WriteLine "Web site:"& objWebServer.ServerComment & "Stopped"
   
   WinThreWebStr "Web site:"& objWebServer.ServerComment,objWebServer.Name  
   
   Case Else
   
   objFile.WriteLine "Web site:"& objWebServer.ServerComment & "Unknown"
   
  End Select
 Next
End Function

IISState.bat contents: 
%systemroot%\system32\inetsrv\APPCMD list sites >E:\Websitestate.txt

%systemroot%\system32\inetsrv\APPCMD list appPool >E:\AppPoolsstate.txt

Diskspace: 
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colDisks = objWMIService.ExecQuery("Select * from Win32_LogicalDisk")

DiskperctRqdothr = 10
DiskperctRqdC = 5
DeviceName="C:"

objFile.WriteLine "######################## Windows Disk Space Details "

For Each objDisk In colDisks  

 pctFreeSpace = Int(((objDisk.FreeSpace / objDisk.Size) * 1000)/10)


 If objDisk.DeviceID = DeviceName Then
  
  If  pctFreeSpace <= DiskperctRqdC Then
   
   Cdrivespace = pctFreeSpace
   objFile.WriteLine "C Drive Free Space before cleanup: " & pctFreeSpace & "%"
   serverDiskSpaceMgnt()
   
  End If 
 Else
  If pctFreeSpace <= DiskperctRqdothr Then
   
   Otherdrivespace = objDisk.DeviceID & " Drive  Space is Less than 10%,. Please Check." 
   
  End If 
  
 End If 

 objFile.WriteLine "DeviceID: " & objDisk.DeviceID  & " Free Space:" & " "  & pctFreeSpace & "%"


Next

IIS Log File Check: 
Dim objFSO
Dim fullfilename
Dim filecomp
Dim moddate
Dim ddiff
Dim restart
Dim filefound
Dim iMsg, iConf, Flds
Dim strServer, strSender, strRecipient, strSubject, strMessage

objFile.WriteLine "Windows cluster failure Details"
'Create a File System Object
Set LblncFilePath = Root.getElementsByTagName("LoadbalanceFilepath")
Set HttpsErlgPath = Root.getElementsByTagName("HTTPErrLogLocation")

LblncFilePath = LblncFilePath.Item(0).text
HttpsErlogfilePath = HttpsErlgPath.Item(0).text

Set objFSO = CreateObject("Scripting.FileSystemObject")

Set oNewestFile = Nothing

sFolder = HttpsErlogfilePath

If objFSO.FolderExists(sFolder) Then

 For Each oFile In objFSO.GetFolder(sFolder).Files
  
  If oNewestFile Is Nothing Then      
   
   Set oNewestFile = oFile    
   
  Else      
   
   If oNewestFile.DateCreated < oFile.DateCreated Then        ' Latest file check
    
    Set oNewestFile = oFile      
   End If    
  End If  
 Next
 'name of the text file

End If

'**********************Log File Read start for error string 
strData = objFSO.OpenTextFile(oNewestFile,ForReading).ReadAll 

'Split the text file into lines

arrLines = Split(strData,  vbCrLf )
Dim errorCtr,curDate,logDate
errorCtr = 0
curDate = Now
'Step through the lines

For Each strLine In arrLines
 Dim searchstr
 searchstr = "Connection_Dropped"

 If InStr(1,strLine,searchstr) > 0 Then
  logDate = Mid(strLine,1,16)
  timeDiff = DateDiff("n",logDate,curDate)
  
  If timeDiff <= 5 Then
   errorCtr = errorCtr + 1
  End  If
 End If

Next

If errorCtr > 5 Then

 WinclstrChk 'call cluster failure funcation with below message and restart below services

objFile.WriteLine "Number of times error occured in last 5 mins: " & errorCtr

 objFile.WriteLine "Connection_Dropped"
  

End If

Windows Cluster Check: 
Function WinclstrChk()

 On Error Resume Next
 Dim objXmlHttp
 Dim strHTML
 incluster = 0
 outcluster = 0
 Const SXH_SERVER_CERT_IGNORE_ALL_SERVER_ERRORS = 13056

 Set ClstrSrvlst = Root.getElementsByTagName("serverIP")

 For Each Sersnm In ClstrSrvlst
  
  Ser =Sersnm.text
  
  USServer = "http://" & Ser & "/loadbalancerping.htm"
  
  'USServer1 = "https://" & Ser & "/PAS/loadbal/LoadBalancer.htm"
  
  Set objXmlHttp = CreateObject("Msxml2.ServerXMLHTTP") 
  
  objXmlHttp.setOption 2, SXH_SERVER_CERT_IGNORE_ALL_SERVER_ERRORS
  
  objXmlHttp.open "GET", USServer, False
  
  objXmlHttp.send
  response1 = objXmlHttp.status
  
  'objXmlHttp.open "GET", USServer1, False
  
  'objXmlHttp.send
  'response2 = objXmlHttp.status
  
  objFile.WriteLine response1
  
  strHTML = objXmlHttp.responseText
  Set objXmlHttp = Nothing
  If (response1 = 200) Then
   outResult = "RPM Server: " & Ser & " is Incluster"
   objFile.WriteLine outResult
   incluster = incluster + 1
   
   WinSrvrClstrFlr(incluster)
  Else
   outResult = "RPM Server: " & Ser & " is Out of cluster"
   objFile.WriteLine outResult
   outcluster = outcluster + 1
   WinSrvrClstrFlr(outcluster)
  End If
 Next


End Function 

Event Viewer Check: 
Set EventVwrCd = Root.getElementsByTagName("SysEventcode")
Set AppEventVwrCd = Root.getElementsByTagName("AppEventcode")
Set EventVwrTime = Root.getElementsByTagName("SysEventVwrMonTm")

EvntVwrTm = EventVwrTime.Item(0).text

Const CONVERT_TO_LOCAL_TIME = True

Set dtmStartDate = CreateObject("WbemScripting.SWbemDateTime")
dtmStartDate.SetVarDate DateAdd("n", EvntVwrTm , Now)' CONVERT_TO_LOCAL_TIME

For Each objEventcode In EventVwrCd

 EventCodepropID= objEventcode.text

 If  (Len(EventCodepropID) > 0) Then
  
  EventVwrCl EventCodepropID,dtmStartDate 
  
 End If

Next  

objFile.WriteLine "######################## Windows Application EventViewer Error Details"

For Each objAppEvntcd In AppEventVwrCd

 AppEvntCdpropID= objAppEvntcd.text

 If  (Len(AppEvntCdpropID) > 0) Then
  
  AppEvntVwrlgg AppEvntCdpropID,dtmStartDate 
  
 End If

Next

Sub EventVwrCl(EventIds,Timems)

 Set colLoggedEvents = objWMIService.ExecQuery _
 ("Select * from Win32_NTLogEvent Where Logfile = 'System' and Type='Error'AND EventCode=" & EventIds & " AND TimeWritten > '" & Timems & "' ")


 For Each objEvent In colLoggedEvents
  
  EventCodeID= objEvent.EventCode
  EvcdDescription= objEvent.Message
  
  If (Len(EventCodeID) > 0) Then
   
   objFile.WriteLine objEvent.EventCode
   objFile.WriteLine objEvent.Message
   objFile.WriteLine objEvent.TimeWritten
   
   EvntVwrCdActn EventCodeID,EvcdDescription 'call custom function to take action based on application requirements
   
  End If
  
 Next

End Sub

Sub AppEvntVwrlgg(appEvntId,Timems)

 Set appLggEvnts = objWMIService.ExecQuery _
 ("Select * from Win32_NTLogEvent Where Logfile = 'Application' and Type='Error'AND EventCode=" & appEvntId & " AND TimeWritten > '" & Timems & "' ")

 For Each objappEvent In appLggEvnts
  
  appEvntID= objappEvent.EventCode
  appEvntDescr= objappEvent.Message
  
  If (Len(appEvntID) > 0) Then
   
   objFile.WriteLine appEvntID
   objFile.WriteLine appEvntDescr
   
   EvntVwrCdActn appEvntID,appEvntDescr 'call custom function to take action based on application requirements
   
  End If
 Next

End Sub

Memory and Process Performance: 
objFile.WriteLine "######################## Monitor Memory Performance"
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
set objRefresher = CreateObject("WbemScripting.SWbemRefresher")
Set colItems = objRefresher.AddEnum _
    (objWMIService, "Win32_PerfFormattedData_PerfOS_Memory").objectSet
objRefresher.Refresh
Set colSettings = objWMIService.ExecQuery _
    ("Select * from Win32_ComputerSystem")
    
    For Each objItem in colItems
       
       avblmem = objItem.AvailableMBytes
       
        objFile.WriteLine "Available Megabytes: " & objItem.AvailableMBytes
       
        Wscript.Sleep 2000
        objRefresher.Refresh
    Next


For Each objComputer In colSettings

Totalphymem = Round(objComputer.TotalPhysicalMemory / 2^20) 

objFile.WriteLine "Total Physical Memory: " & Totalphymem & "MB"

Next

Prcntgphymem = INT((avblmem  / Totalphymem) * 1000)/10

objFile.WriteLine round(Prcntgphymem) &"% Memory IS available"

If round(Prcntgphymem) <= 10 then

strMessage = "<HTML><BODY><b> "& strComputer &": 90% Physical Memory is utilizing! please check.</BODY></HTML>"

SendEmail strMessage
End If


'########################  Monitor Process Performance

objFile.WriteLine "########################  Monitor Process Performance"

Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colProcessList = objWMIService.ExecQuery("Select * from Win32_Process")


For Each objProcess in colProcessList
IF objProcess.Name = "w3wp.exe" then


if Round(objProcess.WorkingSetSize / 2^20) >2000 then

objFile.WriteLine "Process: " & objProcess.Name 
objFile.WriteLine "Process ID: " & objProcess.ProcessID 
objFile.WriteLine "Thread Count: " & objProcess.ThreadCount
objFile.WriteLine "Working Set Size: " &  Round(objProcess.WorkingSetSize / 2^20) & "MB"

strMessage = "<HTML><BODY><b> "& strComputer & " <br/> Process : "&objProcess.Name &" is Running High,<br\>" & Round(objProcess.WorkingSetSize / 2^20) & "MB" &" Utilizing ! please check.</BODY></HTML>"

SendEmail strMessage

end if 

end if 

Next

Server Reboot Check: 
Set colOperatingSystems = objWMIService.ExecQuery _
("Select * from Win32_OperatingSystem")

For Each objOS In colOperatingSystems
 dtmBootup = objOS.LastBootUpTime

 dtmLastBootupTime = CDate(Mid(dtmBootup, 5, 2) & "/" & _
 Mid(dtmBootup, 7, 2) & "/" & Left(dtmBootup, 4) _
 & " " & Mid (dtmBootup, 9, 2) & ":" & _
 Mid(dtmBootup, 11, 2) & ":" & Mid(dtmBootup, _
 13, 2))

 dtmSystemUptimeD = DateDiff("D",dtmLastBootUpTime,Now)

 dtmSystemUptimeM = DateDiff("n", dtmLastBootUpTime, Now)

 x=dtmSystemUptimeM Mod 60 
 dtmSystemUptimeH = (dtmSystemUptimeM-x)/60 
 dtmSystemUptimeM = x 
 If dtmSystemUptimeH >= 24 Then 
  dtmSystemUptimeH = dtmSystemUptimeH Mod 24 
 End If 

 If  dtmSystemUptimeD= 1 Then 
  D=" Day" 
 Else 
  D=" Days" 
 End If 

 If dtmSystemUptimeH = 1 Then 
  H=" Hour" 
 Else 
  H=" Hours" 
 End If 

 If dtmSystemUptimeM = 1 Then 
  M=" Minute" 
 Else 
  M=" Minutes" 
 End If 

 Uptime = dtmSystemUptimeD& D & " " & dtmSystemUptimeH& H&" "&dtmSystemUptimeM & M

 If dtmSystemUptimeD < 1 And dtmSystemUptimeH <1 Then

 strMessage = "<HTML><BODY><b> Server Name :"& strComputer &"Today This Server Is Rebooted please Check </BODY></HTML>"

 SendEmail strMessage

 End If 

 objFile.WriteLine "last server Reboot On " & Uptime

Next


objFile.WriteLine "Log Date " & Now


Comments

Popular posts from this blog

Base 64 encoding and decoding

LINQ Queries with GROUP BY, INNER JOIN, COUNT and SUM: Examples

How to write Custom delete Confirmation Modal for Kendo Grid in MVC: