You are here:
ActiveXperts.com > Support > ActiveXperts Network Monitor > Online > Network Monitor VBScript Guidelines
Quicklinks
VBScript is a subset of Visual Basic that will allow you to include simple to very complex programs in your daily system administration duties. Even though it doesn't support all the features of Visual Basic, it is not a toy language, but a full-featured language with most of the attributes of familiar languages such as C++ or Java. If you've been limited to bat files in your admin tasks, you are painfully aware of the limitations bat files impose on your admin needs. Bat files are simply a sequential list of DOS commands stored in a file with the bat extension. With VBScript you'll have the power to perform almost any task you can imagine. But before you can tap this valuable resource you'll have to master the rudiments of programming.
VBScript programs are executed by the VBScript Engine, which is part of the operating system. VBScript programs can be executed from the Windows Explorer (by double-clicking on a <file>.vbs file), from the command line (by using the CSCRIPT vbscript interpreter) or by calling the VBScript Engine directly. ActiveXperts Network Monitor calls the VBScript Engine through low-level system calls.
To allow Network Monitor to process your VBScript based routine, it must meet the following requirements:
Any commands and functions related to a console or User Interface should be avoided. Keep in mind that the Network Monitor Engine runs as a service, and has no user interface. Message boxes and console output statements may lead to undesirable results and should be avoided. Some objects will not work in Network Monitor:
Also, avoid functions that display a dialog box, like 'InputBox'.
The following code shows a simple program that can be run from the command line:
Option Explicit
Dim SYSEXPLANATION, SYSDATA
Const retvalUnknown = 1
Function IsWeekend()
If WeekDay( Date() ) = VBSaturday or WeekDay( Date() ) = VBSunday Then
SYSEXPLANATION = "Yes, weekend"
SYSDATA = WeekDay( Date() ) ' Optionally, set SYSDATA
IsWeekend = True
Else
SYSEXPLANATION = "No, no weekend"
SYSDATA = WeekDay( Date() ) ' Optionally, set SYSDATA
IsWeekend = False
End If
End Function
Wscript.Echo "IsWeekend: " & IsWeekend() ' Use Wscript ONLY for testing
Wscript.Echo "IsWeekend: " & SYSEXPLANATION
When you copy/paste this code to a new file, and save it as <yourfile>.vbs, you can run it from the command prompt.
To use this script in ActiveXperts Network Monitor, do the following:
So it looks like this:
Option Explicit
Dim SYSEXPLANATION, SYSDATA
Const retvalUnknown = 1
Function IsWeekend()
If WeekDay( Date() ) = VBSaturday or WeekDay( Date() ) = VBSunday Then
SYSEXPLANATION = "Yes, weekend"
SYSDATA = WeekDay( Date() ) ' Optionally, set SYSDATA
IsWeekend = True
Else
SYSEXPLANATION = "No, no weekend"
SYSDATA = WeekDay( Date() ) ' Optionally, set SYSDATA
IsWeekend = False
End If
End Function
Before integrating a new script in the Network Monitor software, test it first from the command line.
The following steps explain how to test a new script from the command line:
ActiveXperts Network Monitor has built-in facilities for notifications, which covers notifications for the majority of the Network Monitor users. However, if you need different schedules, attachments, read replies or other enhanced notification features, you can use custom scripts.
The following VBScript does exactly the same as the built-in e-mail notification call:
--- BEGIN OF SENDEMAIL.VBS ---
Option Explicit
' Make changes to the following constants to use your own SMTP settings
Const STR_MAILSERVER="mail.your-domain.dom"
Const STR_FROMADDRESS="administrator@your-domain.dom"
Const STR_FROMNAME="ActiveXperts Network Monitor"
' Declaration of variables (requires because of the Option Explicit statement)
Dim objArgs, objMail
Dim strArgResult, strArgDisplayName, strArgDate, strArgTime, strArgExplanation
' 5 arguments required. Assign them to variables
strArgResult = WScript.Arguments( 0 )
strArgDisplayName = WScript.Arguments( 1 )
strArgDate = WScript.Arguments( 2 )
strArgTime = WScript.Arguments( 3 )
strArgExplanation = WScript.Arguments( 4 )
Set objMail = CreateObject("ActiveXperts.SmtpMail")
objMail.HostName = STR_MAILSERVER
objMail.FromAddress = STR_FROMADDRESS
objMail.FromName = STR_FROMNAME
objMail.AddTo "recipient1@your-domain.dom", "Recipient1"
objMail.AddTo "recipient2@other-domain.dom", "Recipient2"
objMail.Subject = strArgResult & ": " & strArgDisplayName
objMail.Body = "Message from Network Monitor, " & strArgDate & " " & strArgTime & _
vbCrLf & vbCrLf & _
"Item:" & vbCrLf & " " & strArgDisplayName & vbCrLf & _
"Result:" & vbCrLf & " " & strArgResult & vbCrLf & _
"Explanation:" & vbCrLf & " " & strArgExplanation & vbCrLf
' Send the e-mail
objMail.Send
If( objMail.LastError <> 0 ) Then
Wscript.Echo "Error #" & objMail.LastError
WScript.Echo "Last response from SMTP Server: " & objMail.LastSmtpResponse
End If
--- END OF SMTP.VBS ---
To use the script, you must do the following:
The script uses ActiveXpert's ActiveEmail to send out SMTP messages. ActiveEmail is a commercial product. Registered users of ActiveXperts Network Monitor can use ActiveEmail for free. The Network Monitor license allows you to use all functions of the components for an unlimited period of time.
To read more about ActiveEmail, visit the ActiveEmail web site at www.activexperts.com/smtp-pop3-component. On this site, you also find the ActiveEmail manual and online samples.
You can write similar scripts to notify through SMS or Pager. You can use ActiveXperts SMS Component for that. ActiveXperts SMS and MMS is a commercial product. Registered users can use SMS Component for free. The Network Monitor license allows you to use all functions of the components for an unlimited period of time.
The following VBScript program shows how to send an SMS message through a custom script:
--- BEGIN OF SMS.VBS ---
Option Explicit
' Make changes to the following constants to use your own SMTP settings
Const STR_DEVICE="Standard 56000 bps Modem"
' Declaration of variables (requires because of the Option Explicit statement)
Dim objArgs, objSms
Dim strRecipient, strMessage
' 2 arguments required. Assign them to variables
strRecipient = WScript.Arguments( 0 )
strMessage = WScript.Arguments( 1 )
Set objSms = CreateObject("ActiveXperts.SMSC")
objSms.Device = STR_DEVICE
objSms.LogFile = "c:\smslog.txt" ' Set logfile, for troubleshooting purposes
objSms.Recipient = strRecipient ' International format, e.g.: +44912345678
' Send the message
WScript.Echo "Sending the message..."
objSms.SendMessage 0
If( objSms.LastError <> 0 ) Then
Wscript.Echo "Error #" & objSms.LastError
End If
--- END OF SMS.VBS ---
To learn more about SMS messaging using the SMS Component, please visit the SMS Component Homepage. On this site, you also find the SMS Component manual and online samples.
ActiveXperts Network Monitor includes a debug control to print debug information to a log file while the Network Monitor Engine interpreter runs the script. The debug control is called ActiveXperts.VbDebugger. ActiveXperts.VbDebugger has the following properties:
ActiveXperts.VbDebugger has the following functions:
The following sample shows how to use the debug control:
Option Explicit
Dim SYSEXPLANATION, SYSDATA
Const retvalUnknown = 1
Function IsWeekend()
Set objDebugger = CreateObject( "ActiveXperts.VbDebugger" )
objDebugger.DebugFile = "c:\temp\debug.txt"
objDebugger.ClearDebugFile ' Clear the file is desired
objDebugger.Write "Function WeekDay will be called now... " & vbCrLf
If WeekDay( Date() )= VBSaturday or WeekDay( Date() ) = VBSunday Then
SYSEXPLANATION = "Yes, weekend"
SYSDATA = WeekDay( Date() ) ' Optionally, set SYSDATA
IsWeekend = True
Else
SYSEXPLANATION = "No, no weekend"
SYSDATA = WeekDay( Date() ) ' Optionally, set SYSDATA
IsWeekend = False
End If
objDebugger.WriteLine "Exit IsWeekend"
End Function
The product ships with many VBScript samples, for immediate use. Below, you find some additional samples, to demonstrate how to build more advanced VBScript functions:
--- BEGIN OF MP3.VBS ---
Option Explicit
Dim SYSEXPLANATION, SYSDATA
Const retvalUnknown = 1
' ///////////////////////////////////////////////////////////////////////////////
Function CheckMp3Files( strDirectory )
Dim numMp3Files, objFso, objFolder
Set objFso = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFso.GetFolder("c:\temp")
numMp3Files = CountMp3Files( objFolder )
If( numMp3Files > 0 ) Then
SYSEXPLANATION = numMp3Files & " MP3 files detected"
SYSDATA = numMp3Files
CheckMp3Files = False
Else
SYSEXPLANATION = "No MP3 files detected"
SYSDATA = 0
CheckMp3Files = True
End If
End Function
' ///////////////////////////////////////////////////////////////////////////////
Function CountMp3Files( objFolder )
Dim objSubFolders, objSubFolder
Dim objFiles, objFile
Dim iFileNum
iFileNum = 0
CountMp3Files = 0
Set objFiles = objFolder.Files
If objFiles.Count <> 0 Then
For Each objFile In objFiles
If( InStr( UCase( objFile.Name ), ".MP3" ) <> 0 ) Then
iFileNum = iFileNum + 1
End If
Next
End If
Set objSubFolders = objFolder.SubFolders
If objSubFolders.Count <> 0 Then
For Each objSubFolder In objSubFolders
iFileNum = iFileNum + CountMp3Files( objSubFolder )
Next
End If
CountMp3Files = iFileNum
End Function
--- END OF MP3.VBS ---
The sample below checks if a file has changed. If a file has changed, it is considered as an error. You can make any change to the script to adjust it to your needs. The function compares the modification date with the modification date of the last call. If the modification dates are not equal, the files are assumed to be not the same. Network Monitor needs to store the modification date to a temp file, which will be used in the next call. This is the second parameter of the function. The function FileModificationCheck requires two parameters:
Don't forget to quote the parameters, i.e. "G:\Public\MyDocument.doc", not G:\Public\MyDocument.doc
--- BEGIN OF FILEMODIFICATIONCHECK.VBS ---
Option Explicit
Dim SYSEXPLANATION, SYSDATA
Const retvalUnknown = 1
' ///////////////////////////////////////////////////////////////////////////////
Function FileModificationCheck( strFile, strLogFile )
' Option Explicit
Dim strPrevModDate, strCurrModDate
FileModificationCheck = True
strPrevModDate = Trim( ReadInfo( strLogFile ) )
strCurrModDate = Trim( GetFileModDate( strFile ) )
If( strCurrModDate = "" ) Then
FileModificationCheck = retvalUnknown
SYSEXPLANATION = "File does not exist"
SYSDATA = ""
Exit Function
End If
' Write current date/time info, to be used in next call of FileModificationCheck
WriteInfo strLogFile, strCurrModDate
If( strPrevModDate = "" ) Then
FileModificationCheck = True ' First time consider file as: not changed
SYSEXPLANATION = "File has not changed (first time)"
SYSDATA = ""
Exit Function
End If
If( strPrevModDate = strCurrModDate ) Then
FileModificationCheck = True ' First time consider file as: not changed
SYSEXPLANATION = "File has not changed"
SYSDATA = strCurrModDate
Exit Function
End If
FileModificationCheck = False
SYSEXPLANATION = "File has changed"
End Function
' /////////////////////////////////////////////////////////////////////////////
Function GetFileModDate( strFile )
On Error Resume Next
Dim fso, fsoFile
GetFileModDate = ""
Set fso = CreateObject("Scripting.FileSystemObject")
Set fsoFile = fso.GetFile( strFile )
GetFileModDate = fsoFile.DateLastModified
End Function
' /////////////////////////////////////////////////////////////////////////////
Function WriteInfo( strLogFile, strInfo )
On Error Resume Next
Dim fso, fsoFile, fsoStream
Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FileExists( strFile ) Then
fso.CreateTextFile( strLogFile )
End If
Set fsoFile = fso.GetFile( strLogFile )
Set fsoStream = fsoFile.OpenAsTextStream(2) ' 1=reading, 2=writing, 8=appending,
fsoStream.WriteLine( strInfo )
fsoStream.Close
End Function
' /////////////////////////////////////////////////////////////////////////////
Function ReadInfo( strLogFile )
On Error Resume Next
Dim fso, fsoFile, fsoStream
ReadInfo = ""
Set fso = CreateObject("Scripting.FileSystemObject")
Set fsoStream = fso.OpenTextFile( strLogFile, 1, false )
ReadInfo = fsoStream.ReadLine
fsoStream.Close
End Function
--- END OF FILEMODIFICATIONCHECK.VBS ---
The sample below shows how to check for a particular file on certain times. If the file does NOT exist on a particular time, the result is: ERROR. Otherwise, the result is: SUCCESS. You can use the sample as a base for many VBScript functions (not only file checks):
--- BEGIN OF CHECKFILE.VBS ---
Option Explicit
Dim SYSEXPLANATION, SYSDATA
Const retvalUnknown = 1
' ///////////////////////////////////////////////////////////////////////////////
Function CheckFile( strFilename, hr, min )
On Error Resume Next
Dim fso, fsoFile, fsoStream
Set fso = CreateObject( "Scripting.FileSystemObject")
If Not fso.FileExists( strFilename ) Then
If Hour( Time() ) = hr And Minute( Time() ) > min Then
CheckFile = False
SYSEXPLANATION = "File does not exist and time has passed "& hr & ":"& min & " ERROR!!"
Else
CheckFile = True
SYSEXPLANATION = "File does not exist, but it is not "& hr & ":"& min & " yet"
End If
Else
CheckFile = True
SYSEXPLANATION = "File exists"
End If
End Function
--- END OF CHECKFILE.VBS ---
The sample below shows how to check for directory names on a computer. You'll be able to trace the occurence of special patterns in directory names:
--- BEGIN OF CHECKDIRECTORYNAMES.VBS ---
Option Explicit
Dim SYSEXPLANATION, SYSDATA
Const retvalUnknown = 1
' ///////////////////////////////////////////////////////////////////////////////
Function CheckDirectoryNames( strComputer, strPattern )
On Error Resume Next
Dim objWMIService, colDirectories, objDirectory
Set objWMIService = GetObject( "winmgmts://" & strComputer & "/root/cimv2" )
If( Err.Number <> 0 ) Then
CheckDirectoryNames = retvalUnknown
SYSEXPLANATION = "Unable to connect to WMI service on computer [" & strComputer & "]." & _
"Possible reasons: remote computer is down, has no WMI installed, " & _
"or requires other credentials to access WMI"
Exit Function
End If
Set colDirectories = objWMIService.ExecQuery( "Select * from Win32_Directory" )
If( colDirectories.Count = 0 ) Then
CheckDirectoryNames = retvalUnknown
SYSEXPLANATION = "Unable to query the directories on computer [" & strComputer & "]"
Exit Function
End If
For Each objDirectory In colDirectories
If( Err.Number <> 0 ) Then
CheckDirectoryNames = retvalUnknown
SYSEXPLANATION = "Unable to list directories on computer [" & strComputer & "]"
Exit Function
End If
If( InStr( UCase( objDirectory.Name ), UCase( strPattern ) ) ) Then
CheckDirectoryNames = False
SYSEXPLANATION = "Directory " & Chr(34) & objDirectory.Name & Chr(34) & " contains " & _
Chr(34) & strPattern & Chr(34) & " in its name"
Exit Function
End If
Next
CheckDirectoryNames = True
SYSEXPLANATION = "Pattern " & Chr(34) & strPattern & Chr(34) & " not found in directory names"
End Function
--- END OF CHECKDIRECTORYNAMES.VBS ---
This function checks a logical drives on a computer. If the drive has run out of free space (specified by numBytesFree) then False is returned; otherwise True is returned. Example: CheckLogicalDiskFreeSpace( "server01", "C:", 1000000 ) checks if there is 1MB of free space on C:
--- BEGIN OF CHECKDIRECTORYNAMES.VBS ---
Option Explicit
Dim SYSEXPLANATION, SYSDATA
Const retvalUnknown = 1
' ///////////////////////////////////////////////////////////////////////////////
Function CheckLogicalDiskFreeSpace( strComputer, strDrive, numBytesFree )
On Error Resume Next
Dim objWMIService, colDisks, objDisk
Set objWMIService = GetObject( "winmgmts://" & strComputer & "/root/cimv2" )
If( Err.Number <> 0 ) Then
CheckLogicalDiskFreeSpace = retvalUnknown
SYSEXPLANATION = "Unable to connect to WMI service on computer [" & strComputer & "]." & _
"Possible reasons: remote computer is down, has no WMI installed, " & _
"or requires other credentials to access WMI"
Exit Function
End If
Set colDisks = objWMIService.ExecQuery( "Select * from Win32_LogcalDisk" )
If( colDisks.Count = 0 ) Then
CheckLogicalDiskFreeSpace = retvalUnknown
SYSEXPLANATION = "Unable to list logical disk drives on computer [" & strComputer & "]"
Exit Function
End If
For Each objDisk In colDisks
If( Err.Number <> 0 ) Then
CheckLogicalDiskFreeSpace = retvalUnknown
SYSEXPLANATION = "Unable to list logical disk drives on computer [" & strComputer & "]"
Exit Function
End If
If( InStr( UCase( objDisk.DeviceID ), UCase( strDrive ) ) ) Then
SYSEXPLANATION = "Free space on drive " & objDisk.DeviceID & " = " & objDisk.FreeSpace & _
", minimum required=[" & objDisk.DeviceID & "]"
If( objDisk.FreeSpace < numBytesFree ) Then
CheckLogicalDiskFreeSpace = False
Exit Function
Else
CheckLogicalDiskFreeSpace = True
Exit Function
End If
End If
Next
CheckLogicalDiskFreeSpace = False
SYSEXPLANATION = "Drive [" & strDrive & "] not found"
End Function
--- END OF CHECKDIRECTORYNAMES.VBS ---
This function checks a share on a (remote) computer. If the status of the share is not OK, then False is returned, otherwise True is returned Example: CheckShare( "server01", "public" ) checks if the share \\server01\public exists If it exists and if the status is OK, True is returned. If the status is NOT ok, False is returned
--- BEGIN OF CHECKSHARE.VBS ---
Option Explicit
Dim SYSEXPLANATION, SYSDATA
Const retvalUnknown = 1
' ///////////////////////////////////////////////////////////////////////////////
Function CheckShare( strComputer, strShare )
On Error Resume Next
Dim objWMIService, colShares, objShare
Set objWMIService = GetObject( "winmgmts://" & strComputer & "/root/cimv2" )
If( Err.Number <> 0 ) Then
CheckShare = retvalUnknown
SYSEXPLANATION = "Unable to connect to WMI service on computer [" & strComputer & "]." & _
"Possible reasons: remote computer is down, has no WMI installed, " & _
"or requires other credentials to access WMI"
Exit Function
End If
Set colShares = objWMIService.ExecQuery( "Select * from Win32_Share" )
If( colShares.Count = 0 ) Then
CheckShare = True
SYSEXPLANATION = "No shares found on computer [" & strComputer & "]."
Exit Function
End If
For Each objShare In colShares
If( Err.Number <> 0 ) Then
CheckShare = True
SYSEXPLANATION = "No shares found on computer [" & strComputer & "]."
Exit Function
End If
If( UCase( objShare.Name ) = UCase( strShare ) ) Then
If( UCase( objShare.Status ) <> "OK" ) Then
CheckShare = False
Else
CheckShare = True
End If
SYSEXPLANATION = "Status of share [\\" & strComputer & "\" & strShare & "]: " & objShare.Status
Exit Function
End If
Next
CheckShare = False
SYSEXPLANATION = "Share [\\" & strComputer & "\" & strShare & "] does not exist"
End Function
--- END OF CHECKSHARE.VBS ---
This function checks all floppy drives on a (remote) computer. If one of the floppy drives is NOT OK, or if no floppy drives found, then False is returned. Otherwise, True is returned.
--- BEGIN OF CHECKFLOPPYDRIVES.VBS ---
Option Explicit
Dim SYSEXPLANATION, SYSDATA
Const retvalUnknown = 1
' ///////////////////////////////////////////////////////////////////////////////
Function CheckFloppyDrives( strComputer )
On Error Resume Next
Dim objWMIService, colDrives, objDrive
CheckFloppyDrives = retvalUnknown ' Default return value
Set objWMIService = GetObject( "winmgmts://" & strComputer & "/root/cimv2" )
If( Err.Number <> 0 ) Then
CheckFloppyDrives = retvalUnknown
SYSEXPLANATION = "Unable to connect to WMI service on computer [" & strComputer & "]." & _
"Possible reasons: remote computer is down, has no WMI installed, " & _
"or requires other credentials to access WMI"
Exit Function
End If
Set colDrives = objWMIService.ExecQuery( "Select * from Win32_FloppyDrive" )
If( colDrives.Count = 0 ) Then
CheckFloppyDrives = retvalUnknown
SYSEXPLANATION = "Unable to list floppy drives on computer [" & strComputer & "]"
Exit Function
End If
For Each objDrive In colDrives
If( Err.Number <> 0 ) Then
CheckFloppyDrives = retvalUnknown
SYSEXPLANATION = "Unable to list floppy drives on computer [" & strComputer & "]"
Exit Function
End If
If( objDrive.Status <> "OK" ) Then
CheckFloppyDrives = False
SYSEXPLANATION = "Floppy drive [" & objDrive.Name & "] is: [" & objDrive.Status & "]"
Exit Function
End If
Next
CheckFloppyDrives = True
SYSEXPLANATION = "All floppy drives are OK"
End Function
--- END OF CHECKFLOPPYDRIVES.VBS ---
This function counts the number of records in a database table that match condition 'Phone = 8000002'. If there are one or more records found then True is returned, otherwise False is retuned.
--- BEGIN OF CHECKDATABASE.VBS ---
Option Explicit
Dim SYSEXPLANATION, SYSDATA
Const retvalUnknown = 1
' ///////////////////////////////////////////////////////////////////////////////
Function CheckDatabase( strConnectionString )
Dim objConn, strSqlQuery, RS
CheckDatabase = retvalUnknown ' Default return value
Set objConn = CreateObject( "ADODB.Connection" )
objConn.Open strConnectionString
strSqlQuery = "SELECT Count(*) FROM Customers " & _
"Where Phone = '8000002'"
Set RS = objConn.Execute( strSqlQuery )
If( RS( 0 ) >= 1 ) Then
CheckDatabase = True
Else
CheckDatabase = False
End If
RS.Close
Set RS = Nothing
Set objConn = Nothing
End Function
--- END OF CHECKDATABASE.VBS ---