Javascript must be enabled to download our products and perform other essential functions on the website.

ionicons-v5-m
ionicons-v5-j
Buy Now Download Free Trial
ionicons-v5-m
ionicons-v5-f

Execute Script Monitor

The Execute Script Monitor allows you to write your own custom scripts in the VBScript, JavaScript, PowerShell languages, or via an SSH connection to a host. You can check anything that your script can access. For VBScript, JavaScript and PowerShell, this monitor makes use of the applicable scripting engine that is already installed on nearly all Windows computers.

The script window is where you enter your script. The script can do anything that can be done in the selected language (including creating external components if available) with all the standard restrictions.

There are two Test buttons. One will run the script within the Console. The other will send the script to the monitoring service that is monitoring the target computer (Central Monitoring Service or a Satellite) and run the script there. This helps find any problems that might come up from the script possibly running on a different machine, or running as a different user (the service Log As user).

ionicons-v5-h

Keep in mind that when the script runs, it might run on a different computer than where you are editing it. That means drive mappings, HKEY_CURRENT_USER registry hive, Internet Explorer settings and the currently running user will often be different.

IMPORTANT: Do not show any user interface elements in the script -- they will not be visible in the monitoring service and will block the script from ever completing.

Topics

VBScript
Documentation - Examples
Javascript
Documentation - Examples
PowerShell
Documentation - Examples
SSH
Documentation - Examples

Additional Script Elements

Besides the scripting language's own objects and elements, the following additional global variables and methods are available within each scripting environment:

VBScript

A good VBScript reference is available at: http://msdn.microsoft.com/en-us/library/d1wf56tt.aspx

ComputerName

This read-only string variable is the name of the computer that the monitor is attached to.

Example:

myStr = ComputerName

CustomProp

This function retrieves the named value of a custom property. It checks the Monitor first, and if not found, checks the monitor's owning computer, and then the computer's group, and then the group's parent group, etc. Custom properties can be set on Groups, Computers and Monitors by right-clicking on the item and choosing the Custom Properties menu.

Example:

myStr = CustomProp("NotifyGroupID")

Details

This is a string value. This value is passed to any attached actions as the details for the action (ie the content of an email notification for example).

Example:

Details = "Alert! Can't contact remote system"

FireActions

This is a boolean value. If the value is set to True, actions attached to the monitor will fire. If it is False, they will not fire. The value defaults to False.

Example:

FireActions = true

GetStatID
RecordStat

GetStatID and RecordStat are used together to record numeric data values to the database for reports.

GetStatID is a function that takes a single string value and returns an integer statID. The string value should be a useful name to you, such as the name of the thing you're probing with the script. Including the server/device name in the string would be a good idea if a similar script will run on multiple computers -- it will make it easier to choose the specific data that you want when you create reports.

Example:

statID = GetStatID("ftpSvr1-myObject")


RecordStat is a method that takes two inputs -- the statID obtained from GetStatID above, and the numeric value to record to the database. The time the value is recorded also gets saved to the database for use in line charts, etc.

Example:
RecordStat statID, objectValue

GetValue
StoreValue

GetValue method takes a text name and returns the value that was stored earlier via the StoreValue call described below. If nothing was ever stored with that name, an empty string is returned.

Example:

prevState = GetValue("LastState")

The StoreValue method takes a text name, and a text value and stores it. This named value can be retrieved later (even when the script runs next) via GetValue. Note that these values will be persisted in the configuration database and kept in memory with the monitor, so they should be kept relatively small (a few hundred characters long or less).

Example:

StoreValue "LastState", "1|15|OK"

InventoryValue

Request an inventory value for the current computer, or a different one. An inventory propertyID must be used to specify which inventory value to retrieve. An optional ComputerID value can be used to get the inventory value from a computer other than the current computer. If a property can have multiple values (CPU Names for example), each one will have a newline character appended.

Example:

'returns the Operating System (18) for the current computer myStr = InventoryValue(18)
'returns the Operating System (18) for the current computer (0 means use default) myStr = InventoryValue(18, 0)
'returns the Operating System (18) for computerID 238 myStr = InventoryValue(18, 238)

The inventoryID values are given below. Note that not all computers/devices will have all inventory values, and some may have none (especially if an Inventory Collector monitor is not added to the computer).

Anti-virus Version38
Anti-virus Pattern File39
Anti-virus Pattern File Date40
Anti-virus Status41
Operating System18
OS Architecture19
OS Version20
OS Last Boot Time (_time_t UTC value)21
OS Current Time (_time_t UTC value)22
CPU Count13
CPU Name (multi value)15
CPU Number of Cores (multi value)16
CPU Clock Speed (multi value)17
Display Name6
Drive Status (multi value)23
Domain9
Manufacturer10
Page File size in MB24
RAM in MB14
System Architecture12
System Model11
Time Zone Offset8
Uptime % this month28
Uptime % last month29
MachineID

Returns the numeric value that uniquely identifies this computer (Computer ID - CID) within the application. Useful in conjunction with the External API.

Example:

myID = MachineID

GroupPath

The name of the group that the computer the monitor is attached to belongs in, with child groups delimited with a > (ie, Servers/Devices > Austin > Lab )

Example:

myStr = GroupPath

ReportResults

This method will take the current value of FireActions and Details and report the result as though the monitor had finished. This is a way for a monitor to report multiple individual errors, similarly to how some other monitors have a "report each event separately" check box.

Example:

ReportResults

SendMail

This method sends an email message to the recipient that you choose. This method can also send the email in HTML format if it sees the <!DOCTYPE in the body of the message.

Example:

SendMail "to_address@host.com", "from_address@host.com", "Subject of message", "Body of email message"

SetComputerCustomPropByID

Custom Properties can be used in directory paths, email messages, scripts and other places. Your script can set a Custom Property on a computer by giving it's ID (first parameter). If the ID is 0, the computer the monitor is running on will be targeted.

Example:

SetComputerCustomPropByID 0, "DEVICEID", "BSQL"

ionicons-v5-h

The Custom Property DISPLAYED_NOTES is the value you can set by right-clicking a computer and selecting Notes. Notes show up at the top of a Server Status Report.

Sleep

This VBScript method takes a single integer value, which is the number of milliseconds that the script should stop and sleep. Be careful about using this: causing too many monitors to sleep for very long means other monitors may not get run.

Example:

Sleep 1500
ToLog

This method takes a string value and appends it to the service's log file (useful for debugging scripts). The line will start with MONITOR_SCRIPT_LOG.

Example:

ToLog "Arrived at first loop"
ToLog resultVal

JavaScript

ComputerName

This read-only string variable is the name of the computer that the monitor is attached to.

Example:

myStr = ComputerName;

CustomProp

This function retrieves the named value of a custom property. It checks the Monitor first, and if not found, checks the monitor's owning computer, and then the computer's group, and then the group's parent group, etc. Custom properties can be set on Groups, Computers and Monitors by right-clicking on the item and choosing the Custom Properties menu.

Example:

myStr = CustomProp("NotifyGroupID");

Details

This is a string value. This value is passed to any attached actions as the details for the action (ie the content of an email notification for example).

Example:

Details = "Alert! Can't contact remote system";

FireActions

This is a boolean value. If the value is set to True, actions attached to the monitor will fire. If it is False, they will not fire. The value defaults to False.

Example:

FireActions = true;

GetStatID
RecordStat

GetStatID and RecordStat are used together to record numeric data values to the database for reports.

GetStatID is a function that takes a single string value and returns an integer statID. The string value should be a useful name to you, such as the name of the thing you're probing with the script. Including the server/device name in the string would be a good idea if a similar script will run on multiple computers -- it will make it easier to choose the specific data that you want when you create reports.

Example:

statID = GetStatID("ftpSvr1-myObject");


RecordStat is a method that takes two inputs -- the statID obtained from GetStatID above, and the numeric value to record to the database. The time the value is recorded also gets saved to the database for use in line charts, etc.

Example:
RecordStat(statID, objectValue);

GetValue
StoreValue

GetValue method takes a text name and returns the value that was stored earlier via the StoreValue call described below. If nothing was ever stored with that name, an empty string is returned.

Example:

prevState = GetValue("LastState");

The StoreValue method takes a text name, and a text value and stores it. This named value can be retrieved later (even when the script runs next) via GetValue. Note that these values will be persisted in the configuration database and kept in memory with the monitor, so they should be kept relatively small (a few hundred characters long or less).

Example:

StoreValue("LastState", "1|15|OK");

InventoryValue

Request an inventory value for the current computer, or a different one. An inventory propertyID must be used to specify which inventory value to retrieve. An optional ComputerID value can be used to get the inventory value from a computer other than the current computer. If a property can have multiple values (CPU Names for example), each one will have a newline character appended.

Example:

//returns the Operating System (18) for the current computer myStr = InventoryValue(18);
//returns the Operating System (18) for the current computer (0 means use default) myStr = InventoryValue(18, 0);
//returns the Operating System (18) for computerID 238 myStr = InventoryValue(18, 238);

The inventoryID values are given below. Note that not all computers/devices will have all inventory values, and some may have none (especially if an Inventory Collector monitor is not added to the computer).

Anti-virus Version38
Anti-virus Pattern File39
Anti-virus Pattern File Date40
Anti-virus Status41
Operating System18
OS Architecture19
OS Version20
OS Last Boot Time (_time_t UTC value)21
OS Current Time (_time_t UTC value)22
CPU Count13
CPU Name (multi value)15
CPU Number of Cores (multi value)16
CPU Clock Speed (multi value)17
Display Name6
Drive Status (multi value)23
Domain9
Manufacturer10
Page File size in MB24
RAM in MB14
System Architecture12
System Model11
Time Zone Offset8
Uptime % this month28
Uptime % last month29
MachineID

Returns the numeric value that uniquely identifies this computer (Computer ID - CID) within the application. Useful in conjunction with the External API.

Example:

myID = MachineID;

GroupPath

The name of the group that the computer the monitor is attached to belongs in, with child groups delimited with a > (ie, Servers/Devices > Austin > Lab )

Example:

myStr = GroupPath

ReportResults

This method will take the current value of FireActions and Details and report the result as though the monitor had finished. This is a way for a monitor to report multiple individual errors, similarly to how some other monitors have a "report each event separately" check box.

Example:

ReportResults();

SendMail

This method sends an email message to the recipient that you choose. This method can also send the email in HTML format if it sees the <!DOCTYPE in the body of the message.

Example:

SendMail("to_address@host.com", "from_address@host.com", "Subject of message", "Body of email message");

SetComputerCustomPropByID

Custom Properties can be used in directory paths, email messages, scripts and other places. Your script can set a Custom Property on the computer whose ID is given (first parameter), or use 0 to indicate the computer the monitor is running on should be targeted.

Example:

SetComputerCustomPropByID(0, "DEVICEID", "BSQL");

ionicons-v5-h

The Custom Property DISPLAYED_NOTES is the value you can set by right-clicking a computer and selecting Notes. Notes show up at the top of a Server Status Report.

Sleep

This method takes a single integer value, which is the number of milliseconds that the script should stop and sleep. Be careful about using this: causing too many monitors to sleep for very long means other monitors may not get run.

Example:

Sleep(1500);

ToLog

This method takes a string value and appends it to the service's log file (useful for debugging scripts). The line will start with MONITOR_SCRIPT_LOG.

Example:

ToLog "Arrived at first loop"
ToLog resultVal

PowerShell

PowerShell interaction happens via the $mon object.

$mon.ChangeMonitorStatus

SetMonitorStatus is a function that sets the status of any monitor. This function takes three values: Monitor ID, Monitor Status, and Status Text. The Monitor ID is assigned in the monitoring service and you can find the ID value by showing the IDs from the View menu and then looking in the navigation colunm. If you use 0 for the Monitor ID the function will change the staus of the monitor the action is attached to. There are four statuses that are available: msOK, msAlert, msError, and msDISABLED. The Status Text is the message that you can supply that is listed for the monitor and will be shown in reports.

Example:

$mon.ChangeMonitorStatus(43, $mon.msAlert, "Status changed for monitor")

Possible values:

Monitor StatusValues
OK$mon.msOK
Alert$mon.msAlert
Alert Show as Green$mon.msALERT_GREEN
Alert Show as Red$mon.msALERT_RED
Error$mon.msError
Disabled$mon.msDISABLED
$mon.ComputerName

This read-only string variable is the name of the computer that the monitor is attached to.

Example:

$myStr = $mon.ComputerName

$mon.CustomProp

This function retrieves the named value of a custom property. It checks the Monitor first, and if not found, checks the monitor's owning computer, and then the computer's group, and then the group's parent group, etc. Custom properties can be set on Groups, Computers and Monitors by right-clicking on the item and choosing the Custom Properties menu.

Example:

$myStr = $mon.CustomProp("NotifyGroupID")

$mon.Details

This is a string value. This value is passed to any attached actions as the details for the action (ie the content of an email notification for example).

Example:

$mon.Details = "Alert! Can't contact remote system"

$mon.FireActions

This is a boolean value. If the value is set to True, actions attached to the monitor will fire. If it is False, they will not fire. The value defaults to False.

Example:

$mon.FireActions = $true

$mon.GetCredentials

The GetCredentials function lets your script request credentials for use within the script. The relevent setting must be enabled (disabled by default) in the Security Protected Settings. This function takes two parameters: A server name/key value, and a credential type.

Credential types can be one of: ctWIN, ctESX, ctSSH, ctAWS, ctCUSTOM

Example:

$user = ""
$info = ""
$pass = ""
if ($mon.GetCredentials("TEST-ENV-DB", [PALowPriorityHelper_Net4.CredType]::ctCUSTOM, [ref]$user, [ref]$info, [ref]$pass))
{
   #use credentials
}
else
{
   #failed to get credentials
}

Because of the concern of scripts exfiltrating credentials, we recommend locking monitors or actions that use the GetCredentials function.

$mon.GetMonitorList

GetMonitorList is a function that uses the Server ID to return a list of monitors assigned to the server and the monitor's attributes. The server ID can be for any server and if no server is given the default will be the current server that this monitor is assigned to. The returned value is a Hashtable that can be iterated through to find the value needed.

Example:

$myTable = $mon.GetMonitorList(1)

The monitor's attributes values:

Statusstatus
Error TexterrText
Dependencydepends_on
Titletitle
Error Action IDserrActionIDs
Scheduled Next Run TimenextRun
Time in Error (seconds)inErrSeconds
Fixed Action IDfixedActionIDs
Last Run TimelastRun
$mon.GetServerList

GetServerList is a function that returns a list of servers assigned to a group and the server's attributes. Two parameter are needed for this function; GroupID and include Child Groups. If no GroupID is used the default 0 is used, which is the entire list of servers at the root level. The second parameter is a switch used to return or not return servers that are in child groups under the starting group. Use to 0 to return all servers and 1 to return servers at the parent level only. The returned value is a Hashtable that can be iterated through to find the value needed.

Example:

$myTable = $mon.GetServerList(2, 1)

The server's attributes values:

Server Namename
Group Levelgroup
Group IDgroupID
Statusstatus
Alias for Serveralias
$mon.GetStatID
$mon.RecordStat

GetStatID and RecordStat are used together to record numeric data values to the database for reports.

GetStatID is a function that takes a single string value and returns an integer statID. The string value should be a useful name to you, such as the name of the thing you're probing with the script. Including the server/device name in the string would be a good idea if a similar script will run on multiple computers -- it will make it easier to choose the specific data that you want when you create reports.

Example:

$statID = $mon.GetStatID("ftpSvr1-myObject")


RecordStat is a method that takes two inputs -- the statID obtained from GetStatID above, and the numeric value to record to the database. The time the value is recorded also gets saved to the database for use in line charts, etc.

Example:
$mon.RecordStat($statID, $objectValue)

$mon.GetValue
$mon.StoreValue

The GetValue method takes a text name and returns the value that was stored earlier via the StoreValue call described below. If nothing was ever stored with that name, an empty string is returned.

Example:

$prevState = $mon.GetValue("LastState")

The StoreValue method takes a text name, and a text value and stores it. This named value can be retrieved later (even when the script runs next) via GetValue. Note that these values will be persisted in the configuration database and kept in memory with the monitor, so they should be kept relatively small (a few hundred characters long or less).

Example:

$mon.StoreValue("LastState", "1|15|OK")

$mon.GroupPath

The name of the group that the computer the monitor is attached to belongs in, with child groups delimited with a > (ie, Servers/Devices > Austin > Lab )

Example:

myStr = $mon.GroupPath

$mon.InventoryValue

Request an inventory value for the current computer, or a different one. An inventory propertyID must be used to specify which inventory value to retrieve. An optional ComputerID value can be used to get the inventory value from a computer other than the current computer. If a property can have multiple values (CPU Names for example), each one will have a newline character appended.

Example:

//returns the Operating System (18) for the current computer myStr = $mon.InventoryValue(18);
//returns the Operating System (18) for the current computer (0 means use default) myStr = $mon.InventoryValue(18, 0);
//returns the Operating System (18) for computerID 238 myStr = $mon.InventoryValue(18, 238);

The inventoryID values are given below. Note that not all computers/devices will have all inventory values, and some may have none (especially if an Inventory Collector monitor is not added to the computer).

Anti-virus Version38
Anti-virus Pattern File39
Anti-virus Pattern File Date40
Anti-virus Status41
Operating System18
OS Architecture19
OS Version20
OS Last Boot Time (_time_t UTC value)21
OS Current Time (_time_t UTC value)22
CPU Count13
CPU Name (multi value)15
CPU Number of Cores (multi value)16
CPU Clock Speed (multi value)17
Display Name6
Drive Status (multi value)23
Domain9
Manufacturer10
Page File size in MB24
RAM in MB14
System Architecture12
System Model11
Time Zone Offset8
Uptime % this month28
Uptime % last month29
$mon.MachineID

Returns the numeric value that uniquely identifies this computer (Computer ID - CID) within the application. Useful in conjunction with the External API.

Example:

$myID = $mon.MachineID

$mon.ReportResults

This method will take the current value of FireActions and Details and report the result as though the monitor had finished. This is a way for a monitor to report multiple individual errors, similarly to how some other monitors have a "report each event separately" check box.

Example:

$mon.ReportResults()

$mon.SendMail

This method sends an email message to the recipient that you choose.

Example:

$mon.SendMail("to_address@host.com", "from_address@host.com", "Subject of message", "Body of email message")

$mon.SetComputerCustomPropByID

Custom Properties exist on groups, computers and monitors. This function lets you set the custom property on a computer. You can specify the computer ID in the first parameter, or set it to 0 to indicate the computer the monitor is running on should be targeted.

Example:

$mon.SetComputerCustomPropByID(0, "DEVICEID", "BSQL")

ionicons-v5-h

The Custom Property DISPLAYED_NOTES is the value you can set by right-clicking a computer and selecting Notes. Notes show up at the top of a Server Status Report.

$mon.SetMonitorStatus

SetMonitorStatus is a function that sets the status of the Excute Script monitor if FireActions is set to true (this function is ignored if FireActions is false). There are three statuses that are available: msOK, msAlert, and msError. The default is msAlert.

Example:

$mon.SetMonitorStatus($mon.msAlert)

Possible values:

Monitor StatusValue
OK$mon.msOK
Alert$mon.msAlert
Error$mon.msError
$mon.TargetUsername
$mon.TargetDomain
$mon.TargetPassword

These values return username, domain and password for the target server if BOTH of the below conditions are met:



Example:
MyLoginFunc($mon.TargetDomain, $mon.TargetUsername, $mon.TargetPassword)
$mon.ToLog

This method takes a string value and appends it to the service's log file (useful for debugging scripts). The line will start with MONITOR_SCRIPT_LOG.

Example:

$mon.ToLog "Arrived at first loop"
$mon.ToLog $resultVal
Start-Sleep

The PowerShell cmdlet takes two parameters. The first parameter specifies timer in seconds (-s) or milliseconds (-m) and the second is an integer that specifies period of time.

Example:

Start-Sleep -s 10

SSH

SSH is a little different than the others. In this case, your script will be sent to the remote computer/device to run. The resulting terminal output is scanned for the special keywords below, and they will be 'executed' in the monitoring service when the script finishes. The keywords must start in the very first column to be recognized. One way to achieve this is to output the line with a new line character right before the keyword, as in this example below:

\nPA_Details("There is a problem")

PA_ChangeMonitorStatus(monitorID, status, description)

This is function that lets you pass the monitor ID, a status value, and a test description to set as the new status for the monitor given by the id. The monitor IDs can be obtains in the Console by setting View > Show Object IDs, or from the GET_MONITOR_INFO External API command.

Possible values for status:

Monitor StatusValues
OK1
Alert2
Alert Show as Green17
Alert Show as Red18
Error3
Disabled6


Example:
PA_ChangeMonitorStatus(12, 2, "Alert! Can't contact remote system")

PA_Details(string)

This is a string value. This value is passed to any attached actions as the details for the action (ie the content of an email notification for example). This particular value can span multiple lines. The value is terminated when a ") is seen.

Example:

PA_Details("Alert! Can't contact remote system")

PA_FireActions(boolean)

This is a boolean value. If the value is set to true, actions attached to the monitor will fire. If it is false, they will not fire. The value defaults to false.

Example:

PA_FireActions(true)

PA_RecordStat(stat_name, value)

This 'function' will record a statistic returned from the script to the database. It is equivalent to GetStatID and RecordStat in the other languages above.

The first parameter is a string value. The string value should be a useful name to you, such as the name of the thing you're probing with the script. The second value is a numeric value that will be stored.

Example:

PA_RecordStat("Scans_Per_Second", 45.6)

PA_SendMail(to, from, subject, body)

This method sends an email message to the recipient that you choose.

Example:

PA_SendMail("to_address@host.com", "from_address@host.com", "Subject of message", "Body of email message")

The SSH script can also use replacement variables that are replaced before the script is sent to the host. These include the following:

$CustomProp(propName)$
$CustomProp(propertyName)$ will be replaced with the value of propertyName which came from from the source monitor, source computer or a parent group. It will be blank if the property is not defined.
$Date$
Date in a human-readable format
$Group$
Name of the group that the owning monitor is in (i.e. could be a value like "Routers").
$GroupPath$
Full path name of the group that the owning monitor is in (i.e. could be a value like "Servers/Devices > Boston > Routers")
$Machine$
Name of the target server
$MachineAlias$
Alias of the target server if one has been set. There will be no value (meaning an empty string) if no alias has been set.
$MachineID$
Internal ID representing the target server. These IDs can be obtained using the External API.
$MachineIP$
IP address of the target server
$MonitorType$
Textual name of the monitor type (i.e. "Event Log Monitor")
$NL$
Value that gets turned into a carriage return-newline pair.
$Time$
Human readable time on the monitoring server.

Standard Configuration Options

Like all monitors, this monitor has standard buttons on the right for Adding Actions, setting Advanced Options and setting the Monitor Schedule.

VBScript Examples


Check a database value

Option Explicit
Dim objconnection
Dim objrecordset
Dim strDetails
Dim valToCheck

Const adOpenStatic = 3
Const adLockOptimistic = 3

FireActions = False

Set objconnection = CreateObject("ADODB.Connection")
Set objrecordset = CreateObject("ADODB.Recordset")

objconnection.Open _
 "Provider=SQLOLEDB;Data Source=<data_base_server>;" & _
 "Initial Catalog=<database_name>;" & _
 "User ID=<username>;Password=<password>;"

'ensure there are at least 1000 rows
objrecordset.Open "SELECT COUNT(*) FROM <database_name>", _
 objconnection, adOpenStatic, adLockOptimistic

If objrecordset.RecordCount <> 0 Then
   objrecordset.MoveFirst
   valToCheck = objrecordset.Fields(0)

   If valToCheck < 1000 Then
      strDetails = "There are only " & valToCheck & " rows in the table!"
      FireActions = True
   End If
Else
   strDetails = "CODE RED !!!! Failed to get result!"
   FireActions = True
End If

Details = strDetails

Check files in a directory

dim highCount
highCount = 1000
Set fso = CreateObject("Scripting.FileSystemObject")
Set oSrcFolder = fso.GetFolder("\\server\dir\tocheck")
fileCount = oSrcFolder.Files.Count

if fileCount > highCount then
   FireActions = True
else
   FireActions = False
end if

Check the size of a specific file and record to a database

FileToCheck = "C:\Files\Backup\dump.db"

Set objFSO = CreateObject("Scripting.FileSystemObject")

If objFSO.FileExists(FileToCheck) Then
   Set objFile = objFSO.GetFile(FileToCheck)

   statID = GetStatID(FileToCheck)
   RecordStat statID, objFile.Size

   If objFile.Size < 1000 Then
      FireActions = True
      Details = FileToCheck & " is too small!"
   Else
      FireActions = False
   End If
Else
   FireActions = True
   Details = FileToCheck & " does not exist!"
End If

Check if the newest file is older than 6 hours old (to ensure new files are being created)

DirToCheck = "C:\Logs"
Dim fNewest
set oFolder=createobject("scripting.filesystemobject").getfolder(DirToCheck)
For Each aFile In oFolder.Files
   If fNewest = "" Then
      Set fNewest = aFile
   Else
      If fNewest.DateCreated < aFile.DateCreated Then
         Set fNewest = aFile
      End If
   End If
Next

if fNewest.DateCreated < (DateAdd("h",-6,Now())) then
   FireActions = True
   Details = "NEWEST LOG FILE older than 6 hours (latest file " & fNewest.DateCreated & ")"
else
   FireActions = False
end if

Launch a program and check the result code

Dim objShell
Set objShell = CreateObject("WScript.Shell")
'Spaces in the path below can cause trouble for the Run method
exitCode = objShell.Run("C:\Test\App.exe", 1, True)
Set objShell = Nothing

if (exitCode = 0) then 'assuming 0 means OK in this case
    FireActions = false
    Details = "Everything is OK"
Else
    FireActions = true
    Details = "Test app returned " + exitCode
End If

Check for text in a file

Option Explicit
Dim oFSO, sFile, oFile, sText
Set oFSO = CreateObject("Scripting.FileSystemObject")
sFile = "\\machine\share\textfile.txt"
If oFSO.FileExists(sFile) Then
    Set oFile = oFSO.OpenTextFile(sFile, 1)
    Do While Not oFile.AtEndOfStream
        sText = oFile.ReadLine
        If Trim(sText) = "ERROR" Then
            FireActions = True
        Else
            FireActions = False
        End If
    Loop
    oFile.Close
Else
    FireActions = True
End If

Thanks goes out to Seth Johnson at Williams for this

Monitor UDP ports using Microsoft PortQry

Set p = CreateObject("WScript.Shell").Exec("%COMSPEC% /c c:\portqry.exe -n <server_name> -e 443 -p udp")
Do While p.Status = 0
Sleep "100"
Loop
Details = p.StdOut.ReadAll
if inStr(Details, "NOT LISTENING") then
    FireActions = True
else
    FireActions = false
end if

Thanks goes out to Darrell Swafford at Hardee County Schools for this

Javascript Examples

The Javascript and VBScript scripting engines are identical, other than the syntax of the language. That means you can look at all of the VBScript examples and make simple changes so it uses Javascript syntax. For example:

VBScript:
	Set p = CreateObject("WScript.Shell")
	FireActions = True
	Sleep "100"

Javascript:
	object p = CreateObject("WScript.Shell");
	FireActions = True;
	Sleep(100);

With that in mind, go to the VBScript examples.

PowerShell Examples


Check files in a directory

$mon.FireActions = $false
$mon.Details = ""
$highCount = 1000 
$folder = "C:\Temp"
$files = Get-ChildItem $folder -Force

if ($files.Count -gt $highCount)
{
	$mon.FireActions = $true
	$mon.Details = "File Count is " + $files.Count
}
		

Launch a PS program and record results

$mon.FireActions = $false 
$statID = $mon.GetStatID("VMGUEST1_5z_free") 
$mon.Details= &powershell.exe "c:\skripte\VM_LUN_Freeperc.ps1 VC1 vmguest1_5z" 
$mon.RecordStat($statID, $mon.Details) 
		
Thanks goes out to Peter Strauss at KELAG for this

Monitor AD Sysvol

$Mon.FireActions = $False
$Name = $Mon.ComputerName
$Mon.Details = ""
$Folder = "\\" + $Name + "\Sysvol"

If ((Test-Path $Folder) -eq $False)
{
	$Mon.FireActions = $true
	$Mon.Details = "SYSVOL is not accessible on " + $Name
}
Else
{
	$Mon.Details = "SYSVOL is accessible on " + $Name
	$Mon.FireActions = $False
}	
		
Thanks goes out to Joel Ashman at Progeny Systems Corporation for this

Monitor AD Replication

#Note: Requires AD RSAT tools on PA Server for RepAdmin.exe

$Mon.FireActions = $False
$Mon.Details = ""

$Name = $Mon.ComputerName

$Replication = Repadmin /ShowRepl $Name /CSV | ConvertFrom-CSV | Where {$_.'Number of Failures' -gt 0 } | Select -Unique 'Source DSA' | Sort 'Source DSA'

If ($Replication)
{
	$String = ""
	$String += "The Domain Controller $($Name.ToUpper()) is having difficulty replicating The following servers:`n`n"
$String += " Server`n"
$String += " --------`n"

ForEach ($ReplError in ($Replication ))
{
$Source = $ReplError.'Source DSA'
$String += " " + $Source + "`n"
}
$Mon.FireActions = $True
$Mon.Details = $String
}
Else
{
$Mon.FireActions = $False
$Mon.Details = "Replication is now functioning for Domain Controller " + $Name
}
Thanks goes out to Joel Ashman at Progeny Systems Corporation for this

Monitor Hyper-V VM Status

$vmList = Get-VM
foreach($vm in $vmList)
{
	$mon.Details += $vm.Name + ": " + $vm.State + ", " + $vm.Status + "`r`n"
	if($vm.Status -ne "Operating Normally")
	{
		$mon.FireAlerts = true
	}
}
		

Monitor Window's License Activations

$mon.FireActions = $true
$mon.Details = "Windows OS is NOT activated"

$DNSHostName = $mon.ComputerName
try {
	$wpa = Get-WmiObject SoftwareLicensingProduct -ComputerName $DNSHostName `
	-Filter "ApplicationID = '55c92734-d682-4d71-983e-d6ec3f16059f'" `
	-Property LicenseStatus -ErrorAction Stop
} 
catch {
	$status = New-Object ComponentModel.Win32Exception ($_.Exception.ErrorCode)
	$wpa = $null    
}

$out = New-Object psobject -Property @{
	ComputerName = $DNSHostName;
	Status = [string]::Empty;
}

[bool] $fireAction = $true

if ($wpa) {
	:outer foreach($item in $wpa) {
		switch ($item.LicenseStatus) {
		0 {$out.Status = "Unlicensed"}
		1 {$out.Status = "Licensed"; $fireAction = $false; break outer}
		2 {$out.Status = "Out-Of-Box Grace Period"; break outer}
		3 {$out.Status = "Out-Of-Tolerance Grace Period"; break outer}
		4 {$out.Status = "Non-Genuine Grace Period"; break outer}
		5 {$out.Status = "Notification"; break outer}
		6 {$out.Status = "Extended Grace"; break outer}
		default {$out.Status = "Unknown value"}
		}
	}
} 
else {$out.Status = $status.Message}

if(!$fireAction)
{
	$mon.FireActions = $fireAction
	$mon.Details = $DNSHostName + ": Windows OS is activated"
}
		
Thanks goes out to Joel Ashman at Progeny Systems Corporation for this

SSH Examples

Monitor process memory usage

# The lines highlighted in red are where the SSH script returns information back to the monitor

#--- Set variables here ---

PROCESS_NAME="???" # Run ps -eo comm,pmem to find this
THRESHOLD="30.0" # The percentage memory usage to start firing actions

#--------------------------
AWK_SCRIPT="\$2 ~ /${PROCESS_NAME}/ {memoryusage += \$1} END {print memoryusage}"
MEMUSAGE=`/bin/ps -eo pmem,comm | /usr/bin/awk "${AWK_SCRIPT}"`
TEST_RESULT=`echo "${MEMUSAGE} > ${THRESHOLD}" | /usr/bin/bc -q`
PREPOSITION="below"
if [ ${TEST_RESULT} == "1" ]; then
    echo "PA_FireActions(true)"
    PREPOSITION="above";
fi

echo "PA_Details(\"Memory usage of ${PROCESS_NAME} is ${PREPOSITION} ${THRESHOLD}% (${MEMUSAGE}%)\")"
echo "PA_RecordStat(\"Memory Usage/${PROCESS_NAME}\", ${MEMUSAGE})"
  • Monitor memory of service
  • Your Script


    If you would like to share your script, please contact us.

    PA Storage Monitor

    Help Map