SMS 2003 Monitor SMS Status Messages

SMS_2003_Monitor_SMS_Status_Messages (WriteActionModuleType)

Monitors specific SMS status messages and raises an event with an event ID corresponding to the SMS status message ID

Element properties:

TypeWriteActionModuleType
IsolationAny
AccessibilityInternal
RunAsDefault
InputTypeSystem.BaseData
Comment{D0461B85-2AB1-4A6C-9B81-F73DEBA3AD4E}

Member Modules:

ID Module Type TypeId RunAs 
RunScriptAction WriteAction System.Mom.BackwardCompatibility.ScriptResponse Default

Source Code:

<WriteActionModuleType ID="SMS_2003_Monitor_SMS_Status_Messages" Accessibility="Internal" Comment="{D0461B85-2AB1-4A6C-9B81-F73DEBA3AD4E}">
<Configuration>
<IncludeSchemaTypes>
<SchemaType>MomBackwardCompatibility!System.Mom.BackwardCompatibility.AlertGenerationSchema</SchemaType>
</IncludeSchemaTypes>
<xsd:element xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="AlertGeneration" type="AlertGenerationType"/>
<xsd:element xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="InvokerType" type="xsd:integer"/>
</Configuration>
<ModuleImplementation>
<Composite>
<MemberModules>
<WriteAction ID="RunScriptAction" TypeID="MomBackwardCompatibility!System.Mom.BackwardCompatibility.ScriptResponse">
<AlertGeneration>$Config/AlertGeneration$</AlertGeneration>
<InvokerType>$Config/InvokerType$</InvokerType>
<Body><Script>
'*******************************************************************************
' Script Name - SMS 2003 Monitor SMS Status Messages
'
' Purpose - Monitor specific SMS status messages and raise an event with an
' event ID that corresponds to the SMS status message ID.
'
' The following additional events can be raised:
'
' 1100 - An event used only for debugging or tracing.
' 1101 - Script executed successfully.
' 1102 - An error occurred in executing this script.
' 1105 - Accessed denied due to connection failure or permissions.
'
' Assumptions - This script will run on a system with the SMS SQL Monitor service
' installed. The system must therefore be an SMS Site Database
' Server.
'
' This script does not support agentless mode and will silently
' terminate. This is because of performance reasons and that it
' must proxying on behalf of computers other than the local
' computer it is running on.
'
' The agent will be enabled for proxying for other computers.
'
' Parameters - None
'
' Change Hist - Date Version Description
' -------- --------------- -----------
' 08/27/03 02.50.0102.0000 Added Change History and Patch
' Management messages.
' 09/09/03 02.50.0115.0000 Added Site Backup messages.
' 03/17/04 02.50.0169.0000 Added check for agentless mode.
' 05/17/04 05.0.2700.0000 Added event proxying.
' 09/08/04 05.0.2751.0000 Change to query the SMS Site DB
' directly and not through the SMS WMI
' Provider. Also improved filtering
' on the status message query.
' 10/01/04 05.0.2751.0000 Added status message
' SRVMSG_BACKUP_ERROR_FILESYSTEM_TASK_
' FAILED
' 03/11/05 05.0.2753.0000 Added "Set DATEFORMAT mdy" query
' before querying for SMS status
' messages with a three day filter.
' This resolves previous problem with
' querying on non-english systems.
' 02/19/07 05.0.3132.0000 Added calls to oSQLServer.Disconnect
' in Sub ProcessStatusMessages() to
' fix SQL DMO handle leak.
'
' (c) Copyright 2007, Microsoft Corp., All Rights Reserved
'*******************************************************************************

Option Explicit


'Event Severity Constants
'========================

Const EVENT_TYPE_SUCCESS = 0
Const EVENT_TYPE_ERROR = 1
Const EVENT_TYPE_WARNING = 2
Const EVENT_TYPE_INFORMATION = 4

Const EVENTLOG_AUDIT_SUCCESS = 8
Const EVENTLOG_AUDIT_FAILURE = 16


'SMS Status Message Severity Constants
'=====================================

Const SMS_STATUS_TYPE_SUCCESS = &amp;H00000000
Const SMS_STATUS_TYPE_ERROR = &amp;HC0000000
Const SMS_STATUS_TYPE_WARNING = &amp;H80000000
Const SMS_STATUS_TYPE_INFORMATION = &amp;H40000000

Const SMS_STATUS_TYPE_MASK = &amp;HC0000000


'Event Number Constants
'======================

Const EVENT_ID_NOTANEVENT = 1100
Const EVENT_ID_SCRIPTSUCCESS = 1101
Const EVENT_ID_SCRIPTERROR = 1102
Const EVENT_ID_ACCESSDENIED = 1105


'SMS Status Message IDs
'======================

Const GENMSG_ERROR_NETWORK_SERVER_IS_DOWN = 505
Const GENMSG_ERROR_SQL_CONNECT = 600
Const GENMSG_ERROR_REGISTRY_READ = 672

Const SRVMSG_SITECOMP_ERROR_COMP_INSTALL_FAILED = 1016
Const SRVMSG_SITECOMP_ERROR_COMP_REINSTALL_FAILED = 1020
Const SRVMSG_SITECOMP_ERROR_COMP_DEINSTALL_FAILED_AND_ABORTED = 1025
Const SRVMSG_SITECOMP_ERROR_SERVER_INSTALL_FAILED = 1028
Const SRVMSG_SITECOMP_ERROR_SERVER_DEINSTALL_FAILED_AND_ABORTED = 1035
Const SRVMSG_SITECOMP_ERROR_SERVER_IS_DOWN = 1037
Const SRVMSG_SITECOMP_ERROR_SERVER_IN_USE_BY_OTHER_SITE = 1048
Const SRVMSG_SITECOMP_ERROR_SERVER_NO_NTFS_DRIVE = 1049
Const SRVMSG_SITECOMP_ERROR_SERVER_COULD_NOT_READ_CONNECT_ACCOUNT = 1055
Const SRVMSG_SITECOMP_ERROR_SERVER_COULD_NOT_WRITE_CONNECT_ACCOUNT = 1056
Const SRVMSG_SITECOMP_INFO_TRANSACTION_SERVICE_ACCT_CHANGED = 1062
Const SRVMSG_SITECOMP_INFO_TRANSACTION_DEINSTALL_SERVER = 1069
Const SRVMSG_SITECOMP_INFO_COMP_DEINSTALLED_THREAD = 1097
Const SRVMSG_SITECOMP_INFO_COMP_COULD_NOT_START_THREAD = 1098
Const SRVMSG_SMSEXEC_ERROR_AUTOSTART_THREAD_COMP_STOPPED = 1104
Const SRVMSG_SMSDBMON_WARNING_TASK_EXEC = 2401
Const SRVMSG_COLLEVAL_ERROR_ENUM_COLL = 2500
Const SRVMSG_COLLEVAL_ERROR_SETUP_TABLE = 2514
Const SRVMSG_DDM_ERROR_GET_DISC_SRC = 2601
Const SRVMSG_DATALDR_ERROR_STOPPING_MIF_PROC = 2701
Const SRVMSG_SITECTRL_INFO_DELTA_FROM_SDK_CLIENT_IS_OLD = 2809
Const SRVMSG_HMAN_ERROR_CONNECT_TO_SQL = 3303
Const SRVMSG_HMAN_INFO_PROCESSED_DB = 3307
Const SRVMSG_SCHED_ERROR_NO_ADDRESS_DEFINED = 3400
Const SRVMSG_SENDER_ERROR_LAN_CONNECTION = 3500
Const SRVMSG_SENDER_ERROR_RAS_CONNECTION = 3501
Const SRVMSG_SENDER_ERROR_LAN_CONNECTION2 = 3530
Const SRVMSG_INBOXMGR_ERROR_CONNECT_TO_SITE_SERVER = 3604
Const SRVMSG_SITECOMP_ERROR_SERVER_COMPONENTS_DEINSTALL_FAILED_AND_ABORTED = 4903
Const SRVMSG_SITECOMP_INFO_COMP_COULD_NOT_ADD_MACHINEACCOUNT = 4908
Const SRVMSG_SITECOMP_CANNOT_FIND_SMS_AD_CONTAINER = 4909
Const SRVMSG_SITECOMP_CANNOT_UPDATE_AD_OBJECT = 4912
Const SRVMSG_SITECOMP_CANNOT_CREATE_AD_OBJECT = 4913
Const SRVMSG_SITECOMP_CANNOT_UPDATE_MP_PERMISSIONS = 4916
Const SRVMSG_SITECOMP_SLP_CANNOT_CONNECT_TO_SQL = 4917
Const SRVMSG_SITECOMP_ERROR_COMP_BOOTSTRAP_MP_MSI_ERROR = 4951
Const SRVMSG_BACKUP_ERROR_CONTROL_FILE_OPEN = 5000
Const SRVMSG_BACKUP_ERROR_COULD_NOT_STOP_EXECUTABLE = 5002
Const SRVMSG_BACKUP_ERROR_COULD_NOT_START_EXECUTABLE = 5004
Const SRVMSG_BACKUP_ERROR_COULD_NOT_STOP_SERVICE = 5006
Const SRVMSG_BACKUP_ERROR_COULD_NOT_START_SERVICE = 5008
Const SRVMSG_BACKUP_ERROR_NO_BACKUP_DEST_DIR = 5025
Const SRVMSG_BACKUP_ERROR_INVALID_BACKUP_DEST_DIR = 5026
Const SRVMSG_BACKUP_ERROR_SYNTAX_ERRORS = 5027
Const SRVMSG_BACKUP_ERROR_REGISTRY_TASK_FAILED = 5032
Const SRVMSG_BACKUP_ERROR_DBBACKUP_TASK_FAILED = 5033
Const SRVMSG_BACKUP_INFO_COMPLETED_SUCCESSFULLY = 5035
Const SRVMSG_BACKUP_ERROR_FILESYSTEM_TASK_FAILED = 5043

Const MPMSG_FDM_ERROR_CONNECT_TO_SITE_SERVER = 5400
Const MPMSG_CANNOT_READ_MP_CONFIGURATION = 5410
Const MPMSG_CONNECT_DATABASE_FAILED = 5420
Const MPMSG_WINS_REGISTRATION_FAILED = 5430
Const MPMSG_WINS_UNREGISTRATION_FAILED = 5431
Const MPMSG_WRITE_TO_CCM_SETTINGS_FAILED = 5432
Const MPMSG_UPDATE_MP_SETTINGS_FAILED = 5433
Const MPMSG_START_ALL_MP_MANAGERS_FAILED = 5434
Const MPMSG_HTTP_REQUEST_NONRESPONSIVE = 5436

Const DMPMSG_ERROR_UNEXPECTED = 5700
Const DMPMSG_WARNING_LOW_MEMORY = 5701
Const DMPMSG_ERROR_BAD_DB_CONNECTION = 5702

Const CLIMSG_UPDATESSYNC_ERROR_NO_SITECODE = 11450
Const CLIMSG_UPDATESSYNC_ERROR_NO_PACKAGEID = 11451
Const CLIMSG_UPDATESSYNC_ERROR_NO_SITENAME = 11452
Const CLIMSG_UPDATESSYNC_ERROR_NO_TARGET = 11453
Const CLIMSG_UPDATESSYNC_ERROR_NO_WRITE_ACCESS = 11454
Const CLIMSG_UPDATESSYNC_ERROR_NO_READ_ACCESS = 11455
Const CLIMSG_UPDATESSYNC_ERROR_SYNC_FAILED = 11456
Const CLIMSG_UPDATESSYNC_ERROR_UPDATE_DP = 11458


'WBEM Flag Constants
'===================

Const wbemFlagReturnImmediately = &amp;H10
Const wbemFlagForwardOnly = &amp;H20


'Debug level constants
'=====================

Const DBG_TRACE = 1
Const DBG_WARNING = 2
Const DBG_ERROR = 3
Const DBG_NONE = 4


'Error constants
'===============

Const ERR_INVALID_PARAMETER = &amp;H80070057
Const ERR_DATABASE_DOES_NOT_EXIST = &amp;H80070429
Const ERR_INVALID_TABLE = &amp;H8007065C
Const ERR_DATABASE_FAILURE = &amp;H800710D9


'Other constants
'===============

Const VAR_LAST_RECORD_ID = "LastRecordID"

Const SVC_SMS_SQL_MONITOR = "SMS_SQL_MONITOR"


' Global variables
'=================

Dim g_oUtil ' Utility class for MOM events, logging and registry access.
Dim g_oDictionary ' Stores varset data. Note, only string data can be stored.



Sub Main()

Dim strError


On Error Resume Next


LogMessage DBG_TRACE, ScriptContext.Name &amp; " script starting at local time: " &amp; CStr(Time)

'This script does not support agentless monitoring.
'==================================================

If ScriptContext.IsTargetAgentless Then
LogMessage DBG_TRACE, "No action taken; agentless monitoring is not supported."
LogMessage DBG_TRACE, ScriptContext.Name &amp; " script completed at local time: " &amp; CStr(Time)
Exit Sub
End If

'Initialize utility object and set tracing leve for it.
'======================================================

Set g_oUtil = new Util

If IsEmpty(g_oUtil) Then
LogMessage DBG_TRACE, "Failed to instantiate Util object."
ScriptError "instantiate Util object."
LogMessage DBG_TRACE, ScriptContext.Name &amp; " script completed at local time: " &amp; CStr(Time)
Exit Sub
End If

g_oUtil.SetDebugLevel(g_oUtil.DBG_TRACE)

'Initialize the persistent var set this script uses.
'====================================================

OpenVarSet

If 0 &lt;&gt; Err.number Then
strError = GetErrorString(Err)
LogMessage DBG_ERROR, "Failed to load script variables." &amp; strError
ScriptError "load script variables." &amp; strError
Set g_oUtil = Nothing
LogMessage DBG_TRACE, ScriptContext.Name &amp; " script completed at local time: " &amp; CStr(Time)
Exit Sub
End If

'Process status messages found in the SQL SMS Site Databases on
'this machine.
'==============================================================

ProcessStatusMessages

If 0 &lt;&gt; Err.number Then
strError = GetErrorString(Err)
LogMessage DBG_ERROR, "Failed to process SMS status messages." &amp; strError
ScriptError "process SMS status messages." &amp; strError
End If

'Persist the var set this script uses.
'=====================================

SaveVarSet

If 0 &lt;&gt; Err.number Then
strError = GetErrorString(Err)
LogMessage DBG_ERROR, "Failed to save script variables." &amp; strError
ScriptError "save script variables." &amp; strError
End If

Set g_oUtil = Nothing

LogMessage DBG_TRACE, ScriptContext.Name &amp; " script completed at local time: " &amp; CStr(Time)

End Sub


'******************************************************************************
' Name: ProcessStatusMessages
'
' Purpose: Process status messages found in the SQL SMS site databases on
' this computer.
'
' Parameters: None
'
' Returns: Nothing
'
Sub ProcessStatusMessages()

Dim oSQLServer

Dim strDBName
Dim strComputer
Dim strSiteCode
Dim strSiteServer

Dim intRow

Dim oResults


On Error Resume Next


'Get the name of the local machine.
'==================================

strComputer = ScriptContext.TargetComputer

'Open a connection to the default SQL instance using the SQLDMO.
'===============================================================

Set oSQLServer = CreateObject("SQLDMO.SQLServer")

If Err Then
LogMessage DBG_ERROR, "Failed to create a SQLDMO.SQLServer object."
Set oSQLServer = Nothing
Exit Sub
End if

oSQLServer.LoginSecure = True 'use Windows Authentication Mode

oSQLServer.Connect strComputer

If Err Then
LogMessage DBG_ERROR, "Failed to open a connection using SQLDMO.SQLServer to '" &amp; strComputer &amp; "'."
oSQLServer.Disconnect
Set oSQLServer = Nothing
Exit Sub
End if

'Get a collection of all databases in the default SQL instance.
'==============================================================

Set oResults = oSQLServer.ExecuteWithResults("sp_databases")

If Err Then
LogMessage DBG_ERROR, "Failed to get a list of all databases in the default SQL instance."
oSQLServer.Disconnect
Set oSQLServer = Nothing
Exit Sub
End if

'Check each database to see if it is an SMS Site Database. If it is,
'it will be associated with an SMS Site and therefore have an SMS Site
'Code and Site Server. Verify that the database is active for that
'site before processing status messages in it.
'=====================================================================

For intRow=1 To oResults.Rows

strDBName = oResults.GetColumnString(intRow,1)

GetSMSData strComputer, strDBName, strSiteCode, strSiteServer

If Err Then
LogMessage DBG_TRACE, "'" &amp; strDBName &amp; "' is not an SMS site database."
Err.Clear
Else

LogMessage DBG_TRACE, "'" &amp; strDBName &amp; "' is an SMS site database."
LogMessage DBG_TRACE, "Checking if this database is active in site '" &amp; _
strSiteCode &amp; "' for site server '" &amp; strSiteServer &amp; "'."

If IsSiteDatabaseActive(strComputer, strSiteCode, strSiteServer) Then
LogMessage DBG_TRACE, "The database is active."
LogMessage DBG_TRACE, "Processing status messages in the database."
ProcessStatusMessagesInSiteDatabase strComputer, strDBName
Else
LogMessage DBG_TRACE, "The database is not active."
End If

End If

Next

Set oResults = Nothing
oSQLServer.Disconnect
Set oSQLServer = Nothing

End Sub


'******************************************************************************
' Name: GetSMSData
'
' Purpose: Returns data from the specified SMS Site Database.
'
' Parameters: strComputer Fully qualified computer name for the SQL server.
' strDBName Name of the database to query.
' strSiteCode SMS Site Code returned from the specified database.
' strSiteServer SMS Site Server computer name returned from the
' specified database.
'
' Returns: strSiteCode, strSiteServer
'
Sub GetSMSData(strComputer, strDBName, strSiteCode, strSiteServer)

Dim cnADOConnection
Dim rsSMSData

Dim strParam
Dim strQuery

Dim intRecordCount


On Error Resume Next


'Open a connection to the SMS site database in the default SQL
'instance using the OLE DB provider.
'=============================================================

Set cnADOConnection = CreateObject("ADODB.Connection")

cnADOConnection.Provider = "sqloledb"
cnADOConnection.ConnectionTimeout = 900 '15 minutes
cnADOConnection.CommandTimeout = 900 '15 minutes

strParam = "Server=" &amp; strComputer &amp; ";Database=" &amp; strDBName &amp; ";Trusted_Connection=yes"

cnADOConnection.Open strParam

If Err Then
LogMessage DBG_ERROR, "Failed to connect to the database '" &amp; strDBName &amp; "'."
Set cnADOConnection = Nothing
Exit Sub
End If

'Check if the database is an SMS Site Database by querying the
'SMSData table.
'=============================================================

strQuery = "select * from SMSData"

Set rsSMSData = cnADOConnection.Execute(strQuery)

If Err Then
'LogMessage DBG_ERROR, "Failed to execute SMSData query."
cnADOConnection.Close
Set cnADOConnection = Nothing
Exit Sub
End If

'Get the SMS Site Code and SMS Site Server for the database. There
'should be only one row and therefore only one site code and site
'server in the SMSData table.
'==================================================================

intRecordCount = 0

Do While (Not rsSMSData.EOF)

strSiteCode = rsSMSData("ThisSiteCode").Value
strSiteServer = rsSMSData("SMSSiteServer").Value

intRecordCount = intRecordCount + 1

rsSMSData.MoveNext

Loop

If intRecordCount &lt;&gt; 1 Then
LogMessage DBG_ERROR, "The SMSData contains more than one row is therefore consider corrupted."
Err.Raise ERR_INVALID_TABLE
End If

'Close the connection to the database.
'=====================================

Set rsSMSData = Nothing

cnADOConnection.Close

Set cnADOConnection = Nothing

End Sub


'******************************************************************************
' Name: IsSiteDatabaseActive
'
' Purpose: Checks if there is an active SMS Site Database for the specified
' site and or site server.
'
' Parameters: strComputer Fully qualified computer name for the SQL server.
' strSiteCode SMS Site Code
' strSiteServer SMS Site Server computer name
'
' Returns: True, if an active database is present
' False, if an active database is not present
'
Function IsSiteDatabaseActive(strComputer, strSiteCode, strSiteServer)

Dim strQuery
Dim strNamespace
Dim strRegValue

Dim oService


On Error Resume Next


'Check input parameters.
'=======================

IsSiteDatabaseActive = False

If IsEmpty(strComputer) Or IsEmpty(strSiteCode) Or IsEmpty(strSiteServer) Then
LogMessage DBG_ERROR, "Invalid input parameter."
Exit Function
End If

'Check if the specified site is associated with the one and only
'active SMS Site Database by querying through WMI for the single
'instance of the SMS_SQL_MONITOR service. If the service exists,
'verify that the Operations Management site code for the SMS SQL
'Server is the same as the one specified.
'================================================================

strNamespace = "winmgmts:\\" &amp; strComputer &amp; "\root\cimv2"

strQuery = "select * from Win32_Service where Name='" &amp; SVC_SMS_SQL_MONITOR &amp; "'"

Set oService = WMIExecQuery(strNamespace, strQuery)

If Not Err Then

'Get the Operations Management site code for the SMS SQL Server
'and compare it to the specified site code. If they match, there
'is an active database for this site.
'================================================================

strRegValue = g_oUtil.ReadRegistryStringValue(g_oUtil.HKEY_LOCAL_MACHINE, g_oUtil.REG_KEY_SMS_SERVER_OPMGMT_SQL_SERVER, g_oUtil.REG_VALUE_SMS_SERVER_SITE_CODE)

If IsEmpty(strRegValue) Then
Set oService = Nothing
Err.Clear
Exit Function
End If

If (strRegValue = strSiteCode) Then
IsSiteDatabaseActive = True
Set oService = Nothing
Exit Function
End If

Else
Err.Clear
End If

'There is more than one active SMS Site Database on this computer.
'Check if the specified site server is associated with one of them.
'Query through WMI for the instance of the SMS_SQL_MONITOR service
'supporting the SMS Site Server.
'==================================================================

strQuery = "select * from Win32_Service where Name='" &amp; SVC_SMS_SQL_MONITOR &amp; "_" &amp; strSiteServer &amp; "'"

Set oService = WMIExecQuery(strNamespace, strQuery)

If (Not Err) And (oService.Count = 1) Then
IsSiteDatabaseActive = True
End If

Set oService = Nothing

Err.Clear

End Function


'******************************************************************************
' Name: ProcessStatusMessagesInSiteDatabase
'
' Purpose: Process status messages found in the specified SMS Site Database.
'
' Parameters: strComputer Fully qualified computer name for the SQL server.
' strDBName Name of the SMS Site Database to query.
'
' Returns: Nothing
'
Sub ProcessStatusMessagesInSiteDatabase(strComputer, strDBName)

Dim cnADOConnection
Dim rsStatusMessage

Dim intRecordCount
Dim intLastRecordID

Dim bFilter
Dim bAscendingOrder
Dim bFirstRun

Dim strParam
Dim strQuery
Dim strLastRecordID

Dim bCreateEvents


On Error Resume Next


'Check input parameters.
'=======================

If IsEmpty(strComputer) Or IsEmpty(strDBName) Then
LogMessage DBG_ERROR, "Invalid input parameter."
Err.Raise ERR_INVALID_PARAMETER
Exit Sub
End If

'Get the RecordID for the last status message read from this database.
'If the RecordID is null, 0, this can be considered the first status
'message processing run. Only get and save the RecordID of the last
'message in the database.
'====================================================================

intLastRecordID = GetLastRecordID(strDBName)

If intLastRecordID = "" Then
strLastRecordID = "0"
bFilter = False
bAscendingOrder = False
bFirstRun = True
Else
strLastRecordID = intLastRecordID
bFilter = True
bAscendingOrder = True
bFirstRun = False
End If

LogMessage DBG_TRACE, "The record ID of the previous last status message processed was '" &amp; intLastRecordID &amp; "'."

'Open a connection to the SMS site database in the default SQL
'instance using the OLE DB provider.
'=============================================================

Set cnADOConnection = CreateObject("ADODB.Connection")

cnADOConnection.Provider = "sqloledb"
cnADOConnection.ConnectionTimeout = 900 '15 minutes
cnADOConnection.CommandTimeout = 900 '15 minutes

strParam = "Server=" &amp; strComputer &amp; ";Database=" &amp; strDBName &amp; ";Trusted_Connection=yes"

cnADOConnection.Open strParam

If Err Then
LogMessage DBG_ERROR, "Failed to connect to the SMS Site Database."
Set cnADOConnection = Nothing
Exit Sub
End If

'Set date format for the SMS Status Message query which contains a
'date time filter. The MOM Agent runs under the Locale ID 1033,
'English - United States. If the query is being made to a
'non-english SMS Site Database, we need to tell SQL what format the
'date is in.
'==================================================================

strQuery = "set DATEFORMAT mdy"
LogMessage DBG_TRACE, "Set DATEFORMAT query: " &amp; strQuery

LogMessage DBG_TRACE, "Executing query at local time: " &amp; CStr(Time)
Set rsStatusMessage = cnADOConnection.Execute(strQuery)
LogMessage DBG_TRACE, "Query completed at local time: " &amp; CStr(Time)

If Err Then
LogMessage DBG_ERROR, "Failed to execute set DATEFORMAT query."
cnADOConnection.Close
Set cnADOConnection = Nothing
Exit Sub
End If

'Query for new status messages that are being monitored.
'=======================================================

strQuery = GetSMSStatusMessageQuery(strLastRecordID, bFilter, bAscendingOrder)
LogMessage DBG_TRACE, "SMS Status Message query: " &amp; strQuery

LogMessage DBG_TRACE, "Executing query at local time: " &amp; CStr(Time)
Set rsStatusMessage = cnADOConnection.Execute(strQuery)
LogMessage DBG_TRACE, "Query completed at local time: " &amp; CStr(Time)

If Err Then
LogMessage DBG_ERROR, "Failed to execute status message query."
cnADOConnection.Close
Set cnADOConnection = Nothing
Exit Sub
End If

'Create an event for each returned status message.
'=================================================

intRecordCount = 0

Do While (Not rsStatusMessage.EOF)


'If this is the first processing run, get the RecordID of
'the last message and abort.
'========================================================

If bFirstRun Then
intLastRecordID = rsStatusMessage("RecordID").Value
Exit Do
End If

'If an error occurs while attempting to create the event
'for this SMS status message, stop processing. On the
'the next cycle, processing should resume with this same
'message. Note, if one event should fail to be created
'there is a high probability that all subsequent ones
'will also.
'=======================================================

CreateEvent rsStatusMessage

If Err Then
LogMessage DBG_ERROR, "Failed to create a MOM event for an SMS Status Message."
Exit Do
End If

intRecordCount = intRecordCount + 1
intLastRecordID = rsStatusMessage("RecordID").Value

rsStatusMessage.MoveNext

Loop

'Close the connection to the SMS site database.
'==============================================

cnADOConnection.Close

Set cnADOConnection = Nothing
Set rsStatusMessage = Nothing

'Save the RecordID for the last status message read.
'===================================================

SetLastRecordID strDBName, intLastRecordID

If bFirstRun Then
LogMessage DBG_TRACE, "This is the first run against this database."
LogMessage DBG_TRACE, "Monitoring will start on the next run with status message record ID '" &amp; intLastRecordID &amp; "'."
Else
LogMessage DBG_TRACE, "The total number of status messages processed was '" &amp; intRecordCount &amp; "'."
LogMessage DBG_TRACE, "The record ID of the last status message processed was '" &amp; intLastRecordID &amp; "'."
End If

End Sub


'******************************************************************************
' Name: GetSMSStatusMessageQuery
'
' Purpose: Gets query string for monitored SMS Status Messages.
'
' Parameters: strLastRecordID ID of the last record processed. Returned
' query will specify records with a RecordID
' greater than this value.
' bFilter If TRUE, return query for only specific
' SMS 2003 messages. If FALSE, return query
' for all messages.
' bAscendingOrder If TRUE, return query for ascending order.
' If FALSE, return query for descending order.
'
' Returns: String, a query ordered by RecordID, ascending or descending
'
Function GetSMSStatusMessageQuery(strLastRecordID, bFilter, bAscendingOrder)

Dim strQuery
Dim strDateTimeUTC


'Construct select statement. If filtering, perform a join to filter
'out everything but SMS 2003 status messages. Only properties that
'will be used are specified. If not filtering, return everything.
'This will return the RecordID of the last status message.
'===================================================================

If bFilter Then

strQuery = "select " &amp; _
"System.Netbios_Name0, " &amp; _
"System.Resource_Domain_OR_Workgr0, " &amp; _
"StatusMessage.Component, " &amp; _
"StatusMessage.MessageID, " &amp; _
"StatusMessage.ModuleName, " &amp; _
"StatusMessage.RecordID, " &amp; _
"StatusMessage.Severity, " &amp; _
"StatusMessage.SiteCode, " &amp; _
"StatusMessage.TopLevelSiteCode, " &amp; _
"StatusMessage.Win32Error " &amp; _
"from vStatusMessages AS StatusMessage " &amp; _
"join System_DISC as System on StatusMessage.MachineName=System.Netbios_Name0 " &amp; _
"join Sites as Site on StatusMessage.SiteCode=Site.SiteCode " &amp; _
"where Site.Version like '2.5%' and " &amp; _
"RecordID &gt; " &amp; strLastRecordID &amp; ""

Else

strQuery = "select * from vStatusMessages where RecordID &gt; " &amp; strLastRecordID &amp; ""

End If

'Add filter component if needed.
'===============================

If bFilter Then

'SMS Status Message IDs
'======================

strQuery = strQuery &amp; " and StatusMessage.MessageID in " &amp; _
"(" &amp; _
GENMSG_ERROR_NETWORK_SERVER_IS_DOWN &amp; ", " &amp; _
GENMSG_ERROR_SQL_CONNECT &amp; ", " &amp; _
GENMSG_ERROR_REGISTRY_READ &amp; ", " &amp; _
SRVMSG_SITECOMP_ERROR_COMP_INSTALL_FAILED &amp; ", " &amp; _
SRVMSG_SITECOMP_ERROR_COMP_REINSTALL_FAILED &amp; ", " &amp; _
SRVMSG_SITECOMP_ERROR_COMP_DEINSTALL_FAILED_AND_ABORTED &amp; ", " &amp; _
SRVMSG_SITECOMP_ERROR_SERVER_INSTALL_FAILED &amp; ", " &amp; _
SRVMSG_SITECOMP_ERROR_SERVER_DEINSTALL_FAILED_AND_ABORTED &amp; ", " &amp; _
SRVMSG_SITECOMP_ERROR_SERVER_IS_DOWN &amp; ", " &amp; _
SRVMSG_SITECOMP_ERROR_SERVER_IN_USE_BY_OTHER_SITE &amp; ", " &amp; _
SRVMSG_SITECOMP_ERROR_SERVER_NO_NTFS_DRIVE &amp; ", " &amp; _
SRVMSG_SITECOMP_ERROR_SERVER_COULD_NOT_READ_CONNECT_ACCOUNT &amp; ", " &amp; _
SRVMSG_SITECOMP_ERROR_SERVER_COULD_NOT_WRITE_CONNECT_ACCOUNT &amp; ", " &amp; _
SRVMSG_SITECOMP_INFO_TRANSACTION_SERVICE_ACCT_CHANGED &amp; ", " &amp; _
SRVMSG_SITECOMP_INFO_TRANSACTION_DEINSTALL_SERVER &amp; ", " &amp; _
SRVMSG_SITECOMP_INFO_COMP_DEINSTALLED_THREAD &amp; ", " &amp; _
SRVMSG_SITECOMP_INFO_COMP_COULD_NOT_START_THREAD &amp; ", " &amp; _
SRVMSG_SMSEXEC_ERROR_AUTOSTART_THREAD_COMP_STOPPED &amp; ", " &amp; _
SRVMSG_SMSDBMON_WARNING_TASK_EXEC &amp; ", " &amp; _
SRVMSG_COLLEVAL_ERROR_ENUM_COLL &amp; ", " &amp; _
SRVMSG_COLLEVAL_ERROR_SETUP_TABLE &amp; ", " &amp; _
SRVMSG_DDM_ERROR_GET_DISC_SRC &amp; ", " &amp; _
SRVMSG_DATALDR_ERROR_STOPPING_MIF_PROC &amp; ", " &amp; _
SRVMSG_SITECTRL_INFO_DELTA_FROM_SDK_CLIENT_IS_OLD &amp; ", " &amp; _
SRVMSG_HMAN_ERROR_CONNECT_TO_SQL &amp; ", " &amp; _
SRVMSG_HMAN_INFO_PROCESSED_DB &amp; ", " &amp; _
SRVMSG_SCHED_ERROR_NO_ADDRESS_DEFINED &amp; ", " &amp; _
SRVMSG_SENDER_ERROR_LAN_CONNECTION &amp; ", " &amp; _
SRVMSG_SENDER_ERROR_RAS_CONNECTION &amp; ", " &amp; _
SRVMSG_SENDER_ERROR_LAN_CONNECTION2 &amp; ", " &amp; _
SRVMSG_INBOXMGR_ERROR_CONNECT_TO_SITE_SERVER &amp; ", " &amp; _
SRVMSG_SITECOMP_ERROR_SERVER_COMPONENTS_DEINSTALL_FAILED_AND_ABORTED &amp; ", " &amp; _
SRVMSG_SITECOMP_INFO_COMP_COULD_NOT_ADD_MACHINEACCOUNT &amp; ", " &amp; _
SRVMSG_SITECOMP_CANNOT_FIND_SMS_AD_CONTAINER &amp; ", " &amp; _
SRVMSG_SITECOMP_CANNOT_UPDATE_AD_OBJECT &amp; ", " &amp; _
SRVMSG_SITECOMP_CANNOT_CREATE_AD_OBJECT &amp; ", " &amp; _
SRVMSG_SITECOMP_CANNOT_UPDATE_MP_PERMISSIONS &amp; ", " &amp; _
SRVMSG_SITECOMP_SLP_CANNOT_CONNECT_TO_SQL &amp; ", " &amp; _
SRVMSG_SITECOMP_ERROR_COMP_BOOTSTRAP_MP_MSI_ERROR &amp; ", " &amp; _
SRVMSG_BACKUP_ERROR_CONTROL_FILE_OPEN &amp; ", " &amp; _
SRVMSG_BACKUP_ERROR_COULD_NOT_STOP_EXECUTABLE &amp; ", " &amp; _
SRVMSG_BACKUP_ERROR_COULD_NOT_START_EXECUTABLE &amp; ", " &amp; _
SRVMSG_BACKUP_ERROR_COULD_NOT_STOP_SERVICE &amp; ", " &amp; _
SRVMSG_BACKUP_ERROR_COULD_NOT_START_SERVICE &amp; ", " &amp; _
SRVMSG_BACKUP_ERROR_NO_BACKUP_DEST_DIR &amp; ", " &amp; _
SRVMSG_BACKUP_ERROR_INVALID_BACKUP_DEST_DIR &amp; ", " &amp; _
SRVMSG_BACKUP_ERROR_SYNTAX_ERRORS &amp; ", " &amp; _
SRVMSG_BACKUP_ERROR_REGISTRY_TASK_FAILED &amp; ", " &amp; _
SRVMSG_BACKUP_ERROR_DBBACKUP_TASK_FAILED &amp; ", " &amp; _
SRVMSG_BACKUP_INFO_COMPLETED_SUCCESSFULLY &amp; ", " &amp; _
SRVMSG_BACKUP_ERROR_FILESYSTEM_TASK_FAILED &amp; ", " &amp; _
MPMSG_FDM_ERROR_CONNECT_TO_SITE_SERVER &amp; ", " &amp; _
MPMSG_CANNOT_READ_MP_CONFIGURATION &amp; ", " &amp; _
MPMSG_CONNECT_DATABASE_FAILED &amp; ", " &amp; _
MPMSG_WINS_REGISTRATION_FAILED &amp; ", " &amp; _
MPMSG_WINS_UNREGISTRATION_FAILED &amp; ", " &amp; _
MPMSG_WRITE_TO_CCM_SETTINGS_FAILED &amp; ", " &amp; _
MPMSG_UPDATE_MP_SETTINGS_FAILED &amp; ", " &amp; _
MPMSG_START_ALL_MP_MANAGERS_FAILED &amp; ", " &amp; _
MPMSG_HTTP_REQUEST_NONRESPONSIVE &amp; ", " &amp; _
DMPMSG_ERROR_UNEXPECTED &amp; ", " &amp; _
DMPMSG_WARNING_LOW_MEMORY &amp; ", " &amp; _
DMPMSG_ERROR_BAD_DB_CONNECTION &amp; ", " &amp; _
CLIMSG_UPDATESSYNC_ERROR_NO_SITECODE &amp; ", " &amp; _
CLIMSG_UPDATESSYNC_ERROR_NO_PACKAGEID &amp; ", " &amp; _
CLIMSG_UPDATESSYNC_ERROR_NO_SITENAME &amp; ", " &amp; _
CLIMSG_UPDATESSYNC_ERROR_NO_TARGET &amp; ", " &amp; _
CLIMSG_UPDATESSYNC_ERROR_NO_WRITE_ACCESS &amp; ", " &amp; _
CLIMSG_UPDATESSYNC_ERROR_NO_READ_ACCESS &amp; ", " &amp; _
CLIMSG_UPDATESSYNC_ERROR_SYNC_FAILED &amp; ", " &amp; _
CLIMSG_UPDATESSYNC_ERROR_UPDATE_DP &amp; _
")"

'SMS Server and Patch Management Component names
'===============================================

strQuery = strQuery &amp; " and StatusMessage.Component in " &amp; _
"(" &amp; _
"'SMS_AD_SYSTEM_DISCOVERY_AGENT', " &amp; _
"'SMS_AD_SYSTEM_GROUP_DISCOVERY_AGENT', " &amp; _
"'SMS_AD_USER_DISCOVERY_AGENT', " &amp; _
"'SMS_CLIENT_CONFIG_MANAGER', " &amp; _
"'SMS_CLIENT_INSTALL_DATA_MGR', " &amp; _
"'SMS_COLLECTION_EVALUATOR', " &amp; _
"'SMS_COMPONENT_STATUS_SUMMARIZER', " &amp; _
"'SMS_COURIER_SENDER_CONFIRMATION', " &amp; _
"'SMS_DESPOOLER', " &amp; _
"'SMS_DISCOVERY_DATA_MANAGER', " &amp; _
"'SMS_DISTRIBUTION_MANAGER', " &amp; _
"'SMS_EXECUTIVE', " &amp; _
"'SMS_HIERARCHY_MANAGER', " &amp; _
"'SMS_INBOX_MANAGER', " &amp; _
"'SMS_INBOX_MANAGER_ASSISTANT', " &amp; _
"'SMS_INVENTORY_DATA_LOADER', " &amp; _
"'SMS_INVENTORY_PROCESSOR', " &amp; _
"'SMS_LAN_SENDER', " &amp; _
"'SMS_MP_CONTROL_MANAGER', " &amp; _
"'SMS_MP_DEVICE_MANAGER', " &amp; _
"'SMS_MP_FILE_DISPATCH_MANAGER', " &amp; _
"'SMS_NETWORK_DISCOVERY', " &amp; _
"'SMS_OFFER_MANAGER', " &amp; _
"'SMS_OFFER_STATUS_SUMMARIZER', " &amp; _
"'SMS_POLICY_PROVIDER', " &amp; _
"'SMS_REPLICATION_MANAGER', " &amp; _
"'SMS_REPORTING_POINT', " &amp; _
"'SMS_SCHEDULER', " &amp; _
"'SMS_SITE_BACKUP', " &amp; _
"'SMS_SITE_COMPONENT_MANAGER', " &amp; _
"'SMS_SITE_CONTROL_MANAGER', " &amp; _
"'SMS_SITE_SYSTEM_STATUS_SUMMARIZER', " &amp; _
"'SMS_SOFTWARE_INVENTORY_PROCESSOR', " &amp; _
"'SMS_SOFTWARE_METERING_PROCESSOR', " &amp; _
"'SMS_SQL_MONITOR', " &amp; _
"'SMS_STATUS_MANAGER', " &amp; _
"'SMS_WINNT_SERVER_DISCOVERY_AGENT', " &amp; _
"'Software Updates Sync Tool'" &amp; _
")"

'Date and time starting point
'============================

strDateTimeUTC = GetDateTimeUTCQueryFilter()

strQuery = strQuery &amp; " and " &amp; _
"StatusMessage.Time &gt; '" &amp; strDateTimeUTC &amp; "'"

End If

'Add order by qualifier.
'=======================

strQuery = strQuery &amp; " order by RecordID"

'Add asending or descending specifier for how the results will be
'ordered.
'================================================================

If bAscendingOrder Then
strQuery = strQuery &amp; " asc"
Else
strQuery = strQuery &amp; " desc"
End If

'Return the fully constructed query statement.
'=============================================

GetSMSStatusMessageQuery = strQuery

End Function


'******************************************************************************
' Name: GetDateTimeUTCQueryFilter
'
' Purpose: Gets the date and time in UTC format that is to be used to filter
' status messages.
'
' Parameters: None
'
' Returns: String, a date and time
'
Function GetDateTimeUTCQueryFilter()

Dim DateTimeUTC

On Error Resume Next


'Return a data and time in UTC format that is 3 days earlier than the
'current time.
'====================================================================

DateTimeUTC = DateAdd("d", -3, GetCurrentDateTimeUTC()) 'In days

GetDateTimeUTCQueryFilter = FormatDateTime(DateTimeUTC, vbGeneralDate)

End Function


'******************************************************************************
' Name: GetCurrentDateTimeUTC
'
' Purpose: Gets the current date and time in UTC format.
'
' Parameters: None
'
' Returns: Date, current date and time
'
Function GetCurrentDateTimeUTC()

Dim oTimeZone
Dim oTimeZoneSet
Dim CurrentDateTimeLocal
Dim intBias


On Error Resume Next


'Get the instances of this computer's time zone under the WMI CIMV2
'namespace. There will be only one for the current system. Convert
'the current local time to UTC time; UTC = local time + bias. The
'bias is obtained from the Win32_TimeZone class.
'===================================================================

Set oTimeZoneSet = GetObject("winmgmts:").InstancesOf("Win32_TimeZone")

If Err Then
Err.Clear
Exit Function
End If

If Not IsEmpty(oTimeZoneSet) Then

For Each oTimeZone In oTimeZoneSet

'Convert the current local time to UTC time.
'
'A negative time zone bias indicates that the local time is
'earlier than GMT time, a UTC time with zero bias or offset.
'A negative time zone bias must therefore be added to the
'local time. Likewise, a positive one subtracted. The
'daylight savings bias can be added directly though. Thus
'
'Bias = -TimeZoneBias + DaylightSavingsBias
'UTC = LocalTime + Bias. Bias is in minutes.
'===========================================================

CurrentDateTimeLocal = Now

intBias = -oTimeZone.Bias

If Not IsEmpty(oTimeZone.DaylightDay) Then
intBias = intBias + oTimeZone.DaylightBias
End If

GetCurrentDateTimeUTC = DateAdd("n", intBias, CurrentDateTimeLocal) 'In minutes

Next

Set oTimeZoneSet = Nothing

End If

Err.Clear

End Function


'******************************************************************************
' Name: CreateEvent
'
' Purpose: To generate a MOM event for the specified SMS status message.
'
' Parameters: rsStatusMessage, ADO RecordSet object for an SMS Status Message.
'
Sub CreateEvent(rsStatusMessage)

Dim oEvent

Dim lEventType


On Error Resume Next


'Create MOM event object.
'========================

Set oEvent = ScriptContext.CreateEvent

'Initialize Event Type according to SMS status message severity.
'===============================================================

Select Case (SMS_STATUS_TYPE_MASK And rsStatusMessage("Severity").Value)

Case SMS_STATUS_TYPE_SUCCESS

lEventType = EVENT_TYPE_SUCCESS

Case SMS_STATUS_TYPE_ERROR

lEventType = EVENT_TYPE_ERROR

Case SMS_STATUS_TYPE_WARNING

lEventType = EVENT_TYPE_WARNING

Case SMS_STATUS_TYPE_INFORMATION

lEventType = EVENT_TYPE_INFORMATION

End Select

oEvent.EventType = lEventType

'Initialize other event properties with SMS status message properties.
'=====================================================================

oEvent.EventNumber = rsStatusMessage("MessageID").Value
oEvent.Category = rsStatusMessage("SiteCode").Value

'oEvent.SourceDomain = "DOMAIN" ' Domain of SourceComputer
'oEvent.SourceComputer = "MachineName" ' Must be a MOM Agent

oEvent.LoggingDomain = rsStatusMessage("Resource_Domain_OR_Workgr0").Value ' Domain of LoggingComputer
oEvent.LoggingComputer = rsStatusMessage("Netbios_Name0").Value ' Doesn't have to be a MOM Agent

oEvent.SetEventParameter(rsStatusMessage("Netbios_Name0").Value) ' Parameter1
oEvent.SetEventParameter(rsStatusMessage("ModuleName").Value) ' Parameter2
oEvent.SetEventParameter(rsStatusMessage("Component").Value) ' Parameter3
oEvent.SetEventParameter(rsStatusMessage("MessageID").Value) ' Parameter4
oEvent.SetEventParameter(rsStatusMessage("Win32Error").Value) ' Parameter5
oEvent.SetEventParameter(rsStatusMessage("TopLevelSiteCode").Value) ' Parameter6
oEvent.SetEventParameter(rsStatusMessage("RecordID").Value) ' Parameter7

oEvent.Message = "A new monitored SMS status message on machine " &amp; rsStatusMessage("Netbios_Name0").Value &amp; _
" from component " &amp; rsStatusMessage("Component").Value &amp; _
" with message ID " &amp; rsStatusMessage("MessageID").Value &amp; _
" was found in the site " &amp; rsStatusMessage("SiteCode").Value &amp; _
" database."

'Submit, raise, this event to MOM.
'=================================

ScriptContext.Submit oEvent

'Cleanup
'=======

Set oEvent = Nothing

End Sub


'******************************************************************************
' Name: GetErrorString
'
' Purpose: Attempts to find the description for an error if an error with
' no description is passed in.
'
' Parameters: oErr The error object
'
' Returns: String, the description for the error. (Includes the error code.)
'
Function GetErrorString(oErr)

Dim lErr
Dim strErr


lErr = oErr
strErr = oErr.Description

On Error Resume Next


If 0 &gt;= Len(strErr) Then

'If we don't have an error description, then check to see if the
'error is a 0x8007xxxx error. If it is, then look it up.
'===============================================================

Const ErrorMask = &amp;HFFFF0000
Const HiWord8007 = &amp;H80070000
Const LoWordMask = 65535 ' This is equivalent to 0x0000FFFF

If (lErr And ErrorMask) = HiWord8007 Then

'Attempt to use 'net helpmsg' to get a description for the error.
'================================================================

Dim oShell
Set oShell = CreateObject("WScript.Shell")

If Err = 0 Then

Dim oExec
Set oExec = oShell.Exec("net helpmsg " &amp; (lErr And LoWordMask))

Dim strMessage, i
Do
strMessage = oExec.stdout.ReadLine()
i = i + 1
Loop While (Len(strMessage) = 0) And (i &lt; 5)

strErr = strMessage

End If

End If

End If

GetErrorString = vbCrLf &amp; "The error returned was: '" &amp; strErr &amp; "' " &amp; lErr &amp; " (0x" &amp; Hex(lErr) &amp; ")"

End Function


'******************************************************************************
' Name: ScriptError
'
' Purpose: To generate a warning about a runtime script error.
'
' Parameters: strError The description of the error
'
' Returns: Nothing
'
Sub ScriptError(strError)

LogEvent EVENT_ID_SCRIPTERROR, EVENT_TYPE_WARNING, "encountered a runtime error." &amp; vbCrLf &amp; "Failed to " &amp; strError

End Sub


'******************************************************************************
' Name: LogEvent
'
' Purpose: To generate a MOM event
'
' Parameters: lEventID The event code
' lEventType The severity of the event
' strMessage The message to include in the event
'
' Returns: Nothing
'
Sub LogEvent(lEventID, lEventType, strMessage)

Dim oEvent


On Error Resume Next

Set oEvent = ScriptContext.CreateEvent

oEvent.EventNumber = lEventID
oEvent.EventType = lEventType
oEvent.Message = "The script '" &amp; ScriptContext.Name &amp; "' running under processing rule '" &amp; ScriptContext.ProcessingRule.Name &amp; "' " &amp; strMessage

ScriptContext.Submit oEvent

End Sub


'******************************************************************************
' Name: LogMessage
'
' Purpose: To log a message to ScriptContext and MOM's agent response log.
'
' Parameters: lLevel The debug level for this message i.e. trace,
' warning or error
' strMessage The message to write
'
' Returns: Nothing
'
Sub LogMessage(lLevel, strMessage)

If (lLevel &lt; DBG_NONE) Then

If (lLevel = DBG_ERROR) Then
ScriptContext.Echo "[Error]: " + strMessage
ElseIf (lLevel = DBG_WARNING) Then
ScriptContext.Echo "[Warning]: " + strMessage
ElseIf (lLevel = DBG_TRACE) Then
ScriptContext.Echo "[Trace]:" + strMessage
End If

End If

End Sub


'******************************************************************************
' Name: OpenVarSet
'
' Purpose: Opens a varset file and reads the data from it, into g_oDictionary.
' Only one varset can be open at a single time. Opening a second
' varset will remove the first one. If the first one has not
' been saved then the changes will be lost.
'
' Parameters: None
'
' Returns: Nothing
'
Sub OpenVarSet()

Dim oFSO
Dim oTempFolder
Dim oFile


Set g_oDictionary = CreateObject("Scripting.Dictionary")

Set oFSO = CreateObject("Scripting.FileSystemObject")

If 0 &lt;&gt; Err Then
ScriptError "create Scripting.FileSystemObject." &amp; GetErrorString(Err)
Else

Set oTempFolder = oFSO.GetSpecialFolder(2)

If 0 &lt;&gt; Err Then
ScriptError "find the Temp directory." &amp; GetErrorString(Err)
Else

Set oFile = oFSO.OpenTextFile(oTempFolder.Path &amp; "\" &amp; ScriptContext.Name &amp; ".VarSet", 1, True, -1)

If 0 &lt;&gt; Err Then
ScriptError "open the '" &amp; ScriptContext.Name &amp; ".VarSet' file in the Temp directory." &amp; GetErrorString(Err)
Else

Do Until oFile.AtEndOfStream

Dim strLine, iBreak

strLine = oFile.ReadLine()
iBreak = Instr(strLine, vbTab)
g_oDictionary.Add Left(strLine, iBreak - 1), Mid(strLine, iBreak + 1)

Loop

oFile.Close

End If

End If

End If

End Sub


'******************************************************************************
' Name: SaveVarSet
'
' Purpose: Persistently stores the varset on disk, uses the temp directory.
'
' Parameters: None
'
' Returns: Nothing
'
Sub SaveVarSet()

Dim oFSO
Dim oTempFolder
Dim oFile


Set oFSO = CreateObject("Scripting.FileSystemObject")

If 0 &lt;&gt; Err Then
ScriptError "create Scripting.FileSystemObject." &amp; GetErrorString(Err)
Else

Set oTempFolder = oFSO.GetSpecialFolder(2)

If 0 &lt;&gt; Err Then
ScriptError "find the Temp directory." &amp; GetErrorString(Err)
Else

Set oFile = oFSO.CreateTextFile(oTempFolder.Path &amp; "\" &amp; ScriptContext.Name &amp; ".VarSet", True, True)

If 0 &lt;&gt; Err Then
ScriptError "create the '" &amp; ScriptContext.Name &amp; ".VarSet' file in the Temp directory." &amp; GetErrorString(Err)
Else

Dim aKeys, aItems, lIndex

aKeys = g_oDictionary.Keys
aItems = g_oDictionary.Items

For lIndex = 0 to g_oDictionary.Count - 1
oFile.WriteLine aKeys(lIndex) &amp; vbTab &amp; aItems(lIndex)
Next

oFile.Close

End If

End If

End If

Set g_oDictionary = nothing

End Sub


'******************************************************************************
' Name: GetData
'
' Purpose: Retrieves data out of a varset. Uses the key to determine what
' data to retrieve.
'
' Parameters: strKey, the key of the data to retrieve
'
' Returns: String, the data to return or an empty string
'
Function GetData(strKey)

If g_oDictionary.Exists(strKey) Then
GetData = g_oDictionary.Item(strKey)
Else
GetData = Empty
End If

End Function


'******************************************************************************
' Name: SetData
'
' Purpose: To store data in a varset. If the key exists then the data
' associated with that key is replaced, otherwise the key/data
' combination is added to the varset.
'
' Parameters: strKey, the key of the line to replace
' Data, the data to associate with the key
'
' Returns: Nothing
'
Sub SetData(strKey, Data)

g_oDictionary.Item(strKey) = Data

End Sub


'******************************************************************************
' Name: GetLastRecordID
'
' Purpose: Retrieves previously saved status message RecordID, for the
' the specified site database, out of a varset.
'
' Parameters: strDBName Name of the queried SMS Site Database.
'
' Returns: String, the data to return or zero
'
Function GetLastRecordID(strDBName)

GetLastRecordID = GetData(VAR_LAST_RECORD_ID &amp; "_" &amp; strDBName)

End Function


'******************************************************************************
' Name: SetLastRecordID
'
' Purpose: Saves the specified Record ID, on a per-database basis, in a
' varset. If the key exists, the data associated with that key is
' replaced, otherwise the key/data combination is added to the
' varset.
'
' Parameters: strDBName Name of the queried SMS Site Database.
' intData The Record ID to save.
'
' Returns: Nothing
'
Sub SetLastRecordID(strDBName, intData)

SetData VAR_LAST_RECORD_ID &amp; "_" &amp; strDBName, intData

End Sub


'==========================================================================
' Class: Util
' Description: Wrapper around WMI.
'==========================================================================
Class Util

'---------------
' Constants (Initialized on constructor due to VBS behavior)
'---------------

'Used to indicate to LogMessage when/how to print the message.
Public DBG_NONE
Public DBG_ERROR
Public DBG_WARNING
Public DBG_TRACE

'Internal Debug Level
Private m_nDebugLevel

'Registry hive constants
Public HKEY_CLASSES_ROOT
Public HKEY_CURRENT_USER
Public HKEY_LOCAL_MACHINE
Public HKEY_USERS
Public HKEY_CURRENT_CONFIG
Public HKEY_DYN_CONFIG

'Registry access permissions
Public KEY_QUERY_VALUE
Public KEY_SET_VALUE
Public KEY_CREATE_SUB_KEY
Public KEY_ENUMERATE_SUB_KEYS
Public KEY_NOTIFY
Public KEY_CREATE_LINK
Public DELETE
Public READ_CONTROL
Public WRITE_DAC
Public WRITE_OWNER

'Registry path and key name constants
Public REG_PATH_SERVICES
Public REG_PATH_SERVICES_BASE

Public REG_PATH_SMS
Public REG_PATH_SMS_BASE

Public REG_PATH_SMS_SERVER

Public REG_PATH_SMS_SERVER_OPMGMT_SMS_SERVER_ROLE
Public REG_PATH_SMS_SERVER_OPMGMT_SMS_SERVER_ROLE_BASE

Public REG_PATH_SMS_SERVER_COMPONENTS
Public REG_PATH_SMS_SERVER_COMPONENTS_BASE

Public REG_PATH_SMS_SERVER_SMSEXEC_COMP_BASE

Public REG_PATH_SMS_SERVER_PROVIDERS
Public REG_PATH_SMS_SERVER_PROVIDERS_BASE

Public REG_KEY_SERVICES_CCMEXEC
Public REG_KEY_SERVICES_SMS_EXECUTIVE
Public REG_KEY_SERVICES_SMS_REPORTING_POINT
Public REG_KEY_SERVICES_SMS_SERVER_LOCATOR_POINT

Public REG_KEY_SMS_SERVER_IDENTIFICATION
Public REG_KEY_SMS_SERVER_OPERATIONS_MANAGEMENT
Public REG_KEY_SMS_SERVER_SETUP

Public REG_KEY_SMS_SERVER_OPMGMT_DISTRIBUTION_POINT
Public REG_KEY_SMS_SERVER_OPMGMT_SITE_SERVER
Public REG_KEY_SMS_SERVER_OPMGMT_SQL_SERVER

Public REG_KEY_SMS_SERVER_SMSEXEC_INBOX_MANAGER_ASSISTANT
Public REG_KEY_SMS_SERVER_SMSEXEC_SMS_LAN_SENDER
Public REG_KEY_SMS_SERVER_SMSEXEC_SMS_MP_CONTROL_MANAGER
Public REG_KEY_SMS_SERVER_SMSEXEC_SMS_MP_FILE_DISPATCH_MANAGER

Public REG_KEY_SMS_SERVER_PROVIDERS

'Registry key value name constants
Public REG_VALUE_SERVICES_DISPLAY_NAME

Public REG_VALUE_SMS_SERVER_VERSION
Public REG_VALUE_SMS_SERVER_FULL_VERSION
Public REG_VALUE_SMS_SERVER_SITE_CODE
Public REG_VALUE_SMS_SERVER_PARENT_SITE_CODE
Public REG_VALUE_SMS_SERVER_CENTRAL_SITE
Public REG_VALUE_SMS_SERVER_BINARY_DIRECTORY
Public REG_VALUE_SMS_SERVER_TYPE

'---------------
' Methods
'---------------

'=============
' Method: Class_Initialize
' Description: This is the constructor
' Parameters:
'=============
Private Sub Class_Initialize()

'Initialize Debug level constants
DBG_TRACE = 1
DBG_WARNING = 2
DBG_ERROR = 3
DBG_NONE = 4

'by default only errors are logged
m_nDebugLevel = DBG_ERROR

'Registry hive constants
HKEY_CLASSES_ROOT = &amp;H80000000
HKEY_CURRENT_USER = &amp;H80000001
HKEY_LOCAL_MACHINE = &amp;H80000002
HKEY_USERS = &amp;H80000003
HKEY_CURRENT_CONFIG = &amp;H80000005
HKEY_DYN_CONFIG = &amp;H80000006

'Registry access permissions
KEY_QUERY_VALUE = &amp;H1
KEY_SET_VALUE = &amp;H2
KEY_CREATE_SUB_KEY = &amp;H4
KEY_ENUMERATE_SUB_KEYS = &amp;H8
KEY_NOTIFY = &amp;H10
KEY_CREATE_LINK = &amp;H20
DELETE = &amp;H10000
READ_CONTROL = &amp;H20000
WRITE_DAC = &amp;H40000
WRITE_OWNER = &amp;H80000

'Registry path and key name constants
REG_PATH_SERVICES = "SYSTEM\CurrentControlSet\Services"
REG_PATH_SERVICES_BASE = REG_PATH_SERVICES + "\"

REG_PATH_SMS = "SOFTWARE\Microsoft\SMS"
REG_PATH_SMS_BASE = REG_PATH_SMS + "\"

REG_PATH_SMS_SERVER = REG_PATH_SMS

REG_PATH_SMS_SERVER_OPMGMT_SMS_SERVER_ROLE = REG_PATH_SMS_BASE + "Operations Management\SMS Server Role"
REG_PATH_SMS_SERVER_OPMGMT_SMS_SERVER_ROLE_BASE = REG_PATH_SMS_SERVER_OPMGMT_SMS_SERVER_ROLE + "\"

REG_PATH_SMS_SERVER_COMPONENTS = REG_PATH_SMS_BASE + "COMPONENTS"
REG_PATH_SMS_SERVER_COMPONENTS_BASE = REG_PATH_SMS_SERVER_COMPONENTS + "\"

REG_PATH_SMS_SERVER_SMSEXEC_COMP_BASE = REG_PATH_SMS_SERVER_COMPONENTS_BASE + "SMS_EXECUTIVE\Threads\"

REG_PATH_SMS_SERVER_PROVIDERS = REG_PATH_SMS_BASE + "Providers"
REG_PATH_SMS_SERVER_PROVIDERS_BASE = REG_PATH_SMS_SERVER_PROVIDERS + "\"

REG_KEY_SERVICES_CCMEXEC = REG_PATH_SERVICES_BASE + "CcmExec"
REG_KEY_SERVICES_SMS_EXECUTIVE = REG_PATH_SERVICES_BASE + "SMS_EXECUTIVE"
REG_KEY_SERVICES_SMS_REPORTING_POINT = REG_PATH_SERVICES_BASE + "SMS_REPORTING_POINT"
REG_KEY_SERVICES_SMS_SERVER_LOCATOR_POINT = REG_PATH_SERVICES_BASE + "SMS_SERVER_LOCATOR_POINT"

REG_KEY_SMS_SERVER_IDENTIFICATION = REG_PATH_SMS_BASE + "Identification"
REG_KEY_SMS_SERVER_OPERATIONS_MANAGEMENT = REG_PATH_SMS_BASE + "Operations Management"
REG_KEY_SMS_SERVER_SETUP = REG_PATH_SMS_BASE + "Setup"

REG_KEY_SMS_SERVER_OPMGMT_DISTRIBUTION_POINT = REG_PATH_SMS_SERVER_OPMGMT_SMS_SERVER_ROLE_BASE + "SMS Distribution Point"
REG_KEY_SMS_SERVER_OPMGMT_SITE_SERVER = REG_PATH_SMS_SERVER_OPMGMT_SMS_SERVER_ROLE_BASE + "SMS Site Server"
REG_KEY_SMS_SERVER_OPMGMT_SQL_SERVER = REG_PATH_SMS_SERVER_OPMGMT_SMS_SERVER_ROLE_BASE + "SMS SQL Server"

REG_KEY_SMS_SERVER_SMSEXEC_INBOX_MANAGER_ASSISTANT = REG_PATH_SMS_SERVER_SMSEXEC_COMP_BASE + "SMS_INBOX_MANAGER_ASSISTANT"
REG_KEY_SMS_SERVER_SMSEXEC_SMS_LAN_SENDER = REG_PATH_SMS_SERVER_SMSEXEC_COMP_BASE + "SMS_LAN_SENDER"
REG_KEY_SMS_SERVER_SMSEXEC_SMS_MP_CONTROL_MANAGER = REG_PATH_SMS_SERVER_SMSEXEC_COMP_BASE + "SMS_MP_CONTROL_MANAGER"
REG_KEY_SMS_SERVER_SMSEXEC_SMS_MP_FILE_DISPATCH_MANAGER = REG_PATH_SMS_SERVER_SMSEXEC_COMP_BASE + "SMS_MP_FILE_DISPATCH_MANAGER"

REG_KEY_SMS_SERVER_PROVIDERS = REG_PATH_SMS_SERVER_PROVIDERS

'Registry key value name constants
REG_VALUE_SERVICES_DISPLAY_NAME = "DisplayName"

REG_VALUE_SMS_SERVER_VERSION = "Version"
REG_VALUE_SMS_SERVER_FULL_VERSION = "Full Version"
REG_VALUE_SMS_SERVER_SITE_CODE = "Site Code"
REG_VALUE_SMS_SERVER_PARENT_SITE_CODE = "Parent Site Code"
REG_VALUE_SMS_SERVER_CENTRAL_SITE = "Central Site"
REG_VALUE_SMS_SERVER_BINARY_DIRECTORY = "Binary Directory"
REG_VALUE_SMS_SERVER_TYPE = "Type"

End Sub

'=============
' Method: Class_Terminate
' Description: This is the destructor
' Parameters:
'=============
Private Sub Class_Terminate()
End Sub

'=============
' Method: SetDebugLevel
' Description: To change the debugging output level of information
' generated by this utility.
' Parameters:
' nLevel - Level, either DBG_NONE, DBG_TRACE,
' DBG_WARNING or DBG_ERROR
'=============
Public Sub SetDebugLevel(ByVal nLevel)
m_nDebugLevel = nLevel
End Sub

'=============
' Method: LogMessage
' Description: Log a debug message to ScriptContext
' Parameters:
' nLevel - Debug level for the message that we're logging.
' strMessage - The message to write to the trace.
'=============
Public Sub LogMessage(ByVal nLevel, ByVal strMessage)

If (nLevel &lt;= m_nDebugLevel) Then
If (nLevel = DBG_ERROR) Then
ScriptContext.Echo "[Error]: " + strMessage
ElseIf (nLevel = DBG_WARNING) Then
ScriptContext.Echo "[Warning]: " + strMessage
ElseIf (nLevel = DBG_TRACE) Then
ScriptContext.Echo "[Trace]:" + strMessage
End If
End If

End Sub

'=============
' Method: ReadRegistryStringValue
' Description: Used to read strings from the registry
' Parameters:
' lHive - Registry hive or root i.e. HKEY_LOCAL_MACHINE
' strKeyPath - Key path for the Registry key to read
' (like "SOFTWARE\Microsoft\WindowsNT\CurrentVersion")
' strValueName - Name of the registry value to read (like "SoftwareType")
'
' Returns:
' The value of the registry key specified. "Nothing" if it fails.
' Callee needs to handle null value return.
'=============
Public Function ReadRegistryStringValue(ByVal lHive, ByVal strKeyPath, ByVal strValueName)

Dim oReg
Dim strValueData

'Get registry provider object
Call LogMessage(DBG_TRACE, "Connecting to WMI Registry : " + "winmgmts:\\"+ ScriptContext.TargetComputer+ "\root\default:StdRegProv")
Set oReg = WMIGetObject("winmgmts:\\"+ ScriptContext.TargetComputer+ "\root\default:StdRegProv")

'Read from value from registry
if oReg.GetStringValue(lHive, strKeyPath, strValueName, strValueData) = 0 Then
Call LogMessage(DBG_TRACE, "Value of Registry Key: " + strKeyPath + "\" + strValueName + " = " + strValueData)
ReadRegistryStringValue = strValueData
Else
Call LogMessage(DBG_ERROR, "Reading Registry Key: " + strKeyPath + "\" + strValueName + " Failed!" )
ReadRegistryStringValue = Empty
End If

Set oReg = Nothing

End Function

'=============
' Method: ReadRegistryDWORDValue
' Description: Used to read DWORDs from the registry
' Parameters:
' lHive - Registry hive or root i.e. HKEY_LOCAL_MACHINE
' strKeyPath - Key path for the Registry key to read
' (like "SOFTWARE\Microsoft\WindowsNT\CurrentVersion")
' strValueName - Name of the registry value to read (like "SoftwareType")
'
' Returns:
' The value of the registry key specified. "Nothing" if it fails.
' Callee needs to handle null value return.
'=============
Public Function ReadRegistryDWORDValue(ByVal lHive, ByVal strKeyPath, ByVal strValueName)

Dim oReg
Dim lValueData

'Get registry provider object
Call LogMessage(DBG_TRACE, "Connecting to WMI Registry : " + "winmgmts:\\"+ ScriptContext.TargetComputer+ "\root\default:StdRegProv")
Set oReg = WMIGetObject("winmgmts:\\"+ ScriptContext.TargetComputer+ "\root\default:StdRegProv")

'Read value from registry
if oReg.GetDWORDValue(lHive, strKeyPath, strValueName, lValueData) = 0 Then
Call LogMessage(DBG_TRACE, "Value of Registry Key: " + strKeyPath + "\" + strValueName + " = " &amp; lValueData)
ReadRegistryDWORDValue = lValueData
Else
Call LogMessage(DBG_ERROR, "Reading Registry Key: " + strKeyPath + "\" + strValueName + " Failed!" )
ReadRegistryDWORDValue = Empty
End If

Set oReg = Nothing

End Function

'=============
' Method: EnumRegistryKeys
' Description: Used to enumerate registry keys under a given path
' Parameters:
' lHive - Registry hive or root i.e. HKEY_LOCAL_MACHINE
' strKeyPath - Key path for the Registry key to read
' (like "SOFTWARE\Microsoft\WindowsNT\CurrentVersion")
' Returns:
' The list of registry keys found under the path. "null" if the list is empty
'=============
Public Function EnumRegistryKeys(ByVal lHive, ByVal strKeyPath)

Dim oReg
Dim arrKeys

'Get registry provider object
Call LogMessage(DBG_TRACE, "Connecting to WMI Registry : " + "winmgmts:\\"+ ScriptContext.TargetComputer+ "\root\default:StdRegProv")
Set oReg = WMIGetObject("winmgmts:\\"+ ScriptContext.TargetComputer + "\root\default:StdRegProv")

'Enumerate keys in registry
if oReg.EnumKey(lHive, strKeyPath, arrKeys) = 0 Then
Call LogMessage(DBG_TRACE, "Found [" + arrKeys(0) + "] key in path : " + strKeyPath )
EnumRegistryKeys = arrKeys
Else
Call LogMessage(DBG_ERROR, "Error enumerating Registry Keys under path : " + strKeyPath )
End If

Set oReg = Nothing

End Function

'=============
' Method: CheckRegistryKeyAccess
' Description: Used to check permissions access to a registry key
' Parameters:
' lHive - Registry hive or root i.e. HKEY_LOCAL_MACHINE
' strKeyPath - Key path for the Registry key to check access
' (like "SOFTWARE\Microsoft\WindowsNT\CurrentVersion")
' lAccess - required permissions i.e. KEY_QUERY_VALUE + KEY_SET_VALUE
' Returns:
' True if the specified permissions are present on the registry key else false.
'=============
Public Function CheckRegistryKeyAccess(ByVal lHive, ByVal strKeyPath, ByVal lAccess)

Dim oReg
Dim bGranted

'Get registry provider object
Call LogMessage(DBG_TRACE, "Connecting to WMI Registry : " + "winmgmts:\\"+ ScriptContext.TargetComputer+ "\root\default:StdRegProv")
Set oReg = WMIGetObject("winmgmts:\\"+ ScriptContext.TargetComputer + "\root\default:StdRegProv")

'Check access to the specified registry key
if oReg.CheckAccess(lHive, strKeyPath, lAccess, bGranted) = 0 Then
Call LogMessage(DBG_TRACE, "Required access present on registry key : " + strKeyPath )
CheckRegistryKeyAccess = bGranted
Else
Call LogMessage(DBG_ERROR, "Error checking access on registry keys : " + strKeyPath )
CheckRegistryKeyAccess = False
End If

Set oReg = Nothing

End Function

'=============
' Method: CheckRegistryKeyExists
' Description: Used to check existence of a registry key
' Parameters:
' lHive - Registry hive or root i.e. HKEY_LOCAL_MACHINE
' strKeyPath - Key path for the Registry key to check access
' (like "SOFTWARE\Microsoft\WindowsNT\CurrentVersion")
' Returns:
' True if the registry key exists else false.
'=============
Public Function CheckRegistryKeyExists(ByVal lHive, ByVal strKeyPath)

CheckRegistryKeyExists = CheckRegistryKeyAccess(lHive, strKeyPath, KEY_QUERY_VALUE)

End Function

'=============
' Method: CheckRegistryKeyStringValueExists
' Description: Used to check existence of a registry key string value
' Parameters:
' lHive - Registry hive or root i.e. HKEY_LOCAL_MACHINE
' strKeyPath - Key path for the Registry key to check access
' (like "SOFTWARE\Microsoft\WindowsNT\CurrentVersion")
' Returns:
' True if the string value exists else false.
'=============
Public Function CheckRegistryKeyStringValueExists(ByVal lHive, ByVal strKeyPath, ByVal strValueName)

Dim strValue

strValue = ReadRegistryStringValue(lHive, strKeyPath, strValueName)

If IsEmpty(strValue) Then
CheckRegistryKeyStringValueExists = False
Else
CheckRegistryKeyStringValueExists = True
End If

End Function

'=============
' Method: CheckRegistryKeyDWORDValueExists
' Description: Used to check existence of a registry key DWORD value
' Parameters:
' lHive - Registry hive or root i.e. HKEY_LOCAL_MACHINE
' strKeyPath - Key path for the Registry key to check access
' (like "SOFTWARE\Microsoft\WindowsNT\CurrentVersion")
' Returns:
' True if the DWORD value exists else false.
'=============
Public Function CheckRegistryKeyDWORDValueExists(ByVal lHive, ByVal strKeyPath, ByVal strValueName)

Dim lValue

lValue = ReadRegistryDWORDValue(lHive, strKeyPath, strValueName)

If IsEmpty(lValue) Then
CheckRegistryKeyDWORDValueExists = False
Else
CheckRegistryKeyDWORDValueExists = True
End If

End Function

End Class


'=============
' Method: WMIGetObject
' Description: Returns an object of type SWbemObjectSet
' Parameters:
' sNamespace - A WMI Namespace (ex. winmgmts:\\COMPUTERNAME\ROOT\cimv2).
'=============
Function WMIGetObject(sNamespace)
Dim oWMI
Dim nErrNumber, sErrDescription

On Error Resume Next
Set oWMI = GetObject(sNamespace)
nErrNumber = Err.Number
sErrDescription = Err.Description
On Error Goto 0
If IsEmpty(oWMI) Or nErrNumber &lt;&gt; 0 Then
ScriptContext.Echo "Unable to open WMI Namespace " &amp; sNamespace
Err.Raise 9100, GET_WMI_NO_NAMESPACE_SOURCE(sNamespace), GET_WMI_NO_NAMESPACE_DESCRIPTION(nErrNumber, sErrDescription)
End If

Set WMIGetObject = oWMI

Set oWMI = Nothing
End Function


'=============
' Method: WMIGetInstance
' Description: Returns an object of type SWbemObjectSet
' Parameters:
' sNamespace - A WMI Namespace (ex. winmgmts:\\COMPUTERNAME\ROOT\cimv2).
' sInstance - A WMI Namespace Instance (ex. Win32_OperatingSystem)
'=============
Function WMIGetInstance(sNamespace, sInstance)
Dim oWMI, oInstance
Dim nErrNumber, sErrDescription

On Error Resume Next
Set oWMI = GetObject(sNamespace)
nErrNumber = Err.Number
sErrDescription = Err.Description
On Error Goto 0
If IsEmpty(oWMI) Or nErrNumber &lt;&gt; 0 Then
ScriptContext.Echo "Unable to open WMI Namespace " &amp; sNamespace
Err.Raise 9100, GET_WMI_NO_NAMESPACE_SOURCE(sNamespace), GET_WMI_NO_NAMESPACE_DESCRIPTION(nErrNumber, sErrDescription)
End If

On Error Resume Next
Set oInstance = oWMI.InstancesOf(sInstance)
nErrNumber = Err.Number
sErrDescription = Err.Description
On Error Goto 0
If IsEmpty(oInstance) Or nErrNumber &lt;&gt; 0 Then
ScriptContext.Echo "The class name '" &amp; sInstance &amp; "' returned no instances. Error:" &amp; nErrNumber &amp; ", " &amp; sErrDescription &amp; "."
Err.Raise 9100, GET_WMI_NO_INSTANCES_SOURCE(sInstance), GET_WMI_NO_INSTANCES_DESCRIPTION(nErrNumber, sErrDescription)
End If

'Determine if we queried a valid WMI class - Count will return 0 or empty
On Error Resume Next
Dim nInstanceCount
nInstanceCount = oInstance.Count
nErrNumber = Err.Number
sErrDescription = Err.Description
On Error Goto 0
If nErrNumber &lt;&gt; 0 Then
ScriptContext.Echo "The class name '" &amp; sInstance &amp; "' did not return any valid instances. Error:" &amp; nErrNumber &amp; ", " &amp; sErrDescription &amp; "."
Err.Raise 9100, GET_WMI_NO_VALID_INSTANCES_SOURCE(sInstance), GET_WMI_NO_VALID_INSTANCES_DESCRIPTION(nErrNumber, sErrDescription)
End If

Set WMIGetInstance = oInstance

Set oInstance = Nothing
Set oWMI = Nothing
End Function


'=============
' Method: WMIExecQuery
' Description: Returns an object of type SWbemObjectSet
' Parameters:
' sNamespace - A WMI Namespace (ex. winmgmts:\\COMPUTERNAME\ROOT\cimv2).
' sQuery - A SQL Query (ex. SELECT * FROM Win32_OperatingSystem)
'=============
Function WMIExecQuery(sNamespace, sQuery)
Dim oWMI, oQuery
Dim nErrNumber, sErrDescription

On Error Resume Next
Set oWMI = GetObject(sNamespace)
nErrNumber = Err.Number
sErrDescription = Err.Description
On Error Goto 0

If IsEmpty(oWMI) Or nErrNumber &lt;&gt; 0 Then
ScriptContext.Echo "Unable to open WMI Namespace " &amp; sNamespace
Err.Raise 9100, GET_WMI_NO_NAMESPACE_SOURCE(sNamespace), GET_WMI_NO_NAMESPACE_DESCRIPTION(nErrNumber, sErrDescription)
End If

On Error Resume Next
Set oQuery = oWMI.ExecQuery(sQuery)
nErrNumber = Err.Number
sErrDescription = Err.Description
On Error Goto 0
If IsEmpty(oQuery) Or nErrNumber &lt;&gt; 0 Then
ScriptContext.Echo "The Query '" &amp; sQuery &amp; "' returned an invalid result set. Error:" &amp; nErrNumber &amp; ", " &amp; sErrDescription &amp; "."
Err.Raise 9100, GET_WMI_QUERY_NO_RESULTS_SOURCE(sQuery), GET_WMI_QUERY_NO_RESULTS_DESCRIPTION(nErrNumber, sErrDescription)
End If

'Determine if we queried a valid WMI class - Count will return 0 or empty
On Error Resume Next
Dim nInstanceCount
nInstanceCount = oQuery.Count
nErrNumber = Err.Number
sErrDescription = Err.Description
On Error Goto 0
If nErrNumber &lt;&gt; 0 Then
ScriptContext.Echo "The Query '" &amp; sQuery &amp; "' did not return any valid instances. Error:" &amp; nErrNumber &amp; ", " &amp; sErrDescription &amp; "."
Err.Raise 9100, GET_WMI_QUERY_NO_VALID_INSTANCES_SOURCE(sQuery), GET_WMI_QUERY_NO_VALID_INSTANCES_DESCRIPTION(nErrNumber, sErrDescription)
End If

Set WMIExecQuery = oQuery

Set oQuery = Nothing
Set oWMI = Nothing

End Function</Script></Body>
<Language>VBScript</Language>
<Name>SMS 2003 Monitor SMS Status Messages</Name>
<Parameters/>
<ManagementPackId>[Microsoft.SMS.2003,,1.0.0.1]</ManagementPackId>
</WriteAction>
</MemberModules>
<Composition>
<Node ID="RunScriptAction"/>
</Composition>
</Composite>
</ModuleImplementation>
<InputType>SystemLibrary!System.BaseData</InputType>
</WriteActionModuleType>