SQL 2008 Agent Job Status Provider

Microsoft.SQLServer.2008.AgentJobStatus (DataSourceModuleType)

Element properties:

TypeDataSourceModuleType
IsolationAny
AccessibilityInternal
RunAsMicrosoft.SQLServer.SQLProbeAccount
OutputTypeSystem.PropertyBagData

Member Modules:

ID Module Type TypeId RunAs 
DS DataSource Microsoft.Windows.TimedScript.PropertyBagProvider Default

Overrideable Parameters:

IDParameterTypeSelectorDisplay NameDescription
IntervalSecondsint$Config/IntervalSeconds$Interval (sec)
SyncTimestring$Config/SyncTime$Synchronization Time
TimeoutSecondsint$Config/TimeoutSeconds$Timeout (sec)

Source Code:

<DataSourceModuleType ID="Microsoft.SQLServer.2008.AgentJobStatus" Accessibility="Internal" RunAs="SQL!Microsoft.SQLServer.SQLProbeAccount">
<Configuration>
<xsd:element xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="IntervalSeconds" type="xsd:integer"/>
<xsd:element xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="SyncTime" type="xsd:string"/>
<xsd:element xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="ConnectionString" type="xsd:string"/>
<xsd:element xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="TimeoutSeconds" type="xsd:int"/>
</Configuration>
<OverrideableParameters>
<OverrideableParameter ID="IntervalSeconds" ParameterType="int" Selector="$Config/IntervalSeconds$"/>
<OverrideableParameter ID="SyncTime" ParameterType="string" Selector="$Config/SyncTime$"/>
<OverrideableParameter ID="TimeoutSeconds" ParameterType="int" Selector="$Config/TimeoutSeconds$"/>
</OverrideableParameters>
<ModuleImplementation>
<Composite>
<MemberModules>
<DataSource ID="DS" TypeID="Windows!Microsoft.Windows.TimedScript.PropertyBagProvider">
<IntervalSeconds>$Config/IntervalSeconds$</IntervalSeconds>
<SyncTime>$Config/SyncTime$</SyncTime>
<ScriptName>GetSQL2008AgentJobStatus.vbs</ScriptName>
<Arguments>"$Config/ConnectionString$" "$Target/Host/Host/Property[Type="SQL!Microsoft.SQLServer.DBEngine"]/TcpPort$" "$Target/Host/Host/Host/Property[Type="Windows!Microsoft.Windows.Computer"]/NetworkName$" "$Target/Host/Host/Property[Type="SQL!Microsoft.SQLServer.DBEngine"]/ServiceName$" "$Target/Host/Host/Property[Type="SQL!Microsoft.SQLServer.ServerRole"]/InstanceName$"</Arguments>
<ScriptBody><Script>'#Include File:Initialize.vbs

Option Explicit
SetLocale("en-us")

Const ManagementGroupName = "$Target/ManagementGroup/Name$"
Const ManagementGroupID = "$Target/ManagementGroup/Id$"
Const SQL_DEFAULT = "MSSQLSERVER"

Function Quit()
WScript.Quit()
End Function

Function IsValidObject(ByVal oObject)
IsValidObject = False

If IsObject(oObject) Then
If Not oObject Is Nothing Then
IsValidObject = True
End If
End If
End Function

Function MomCreateObject(ByVal sProgramId)
Dim oError
Set oError = New Error

On Error Resume Next
Set MomCreateObject = CreateObject(sProgramId)
oError.Save
On Error GoTo 0

If oError.Number &lt;&gt; 0 Then ThrowScriptError "Unable to create automation object '" &amp; sProgramId &amp; "'", oError
End Function

Public Function GetSQLServiceName(sInstance)
If sInstance = SQL_DEFAULT Then
GetSQLServiceName = SQL_DEFAULT
Else
GetSQLServiceName = "MSSQL$" &amp; sInstance
End If
End Function

'The function returns service or "Unknown" state
'Input:
' server - compute name
' service - system service name
'Output:
' service state or "Unknown" state
Function GetServiceState( sTargetComputer, sServiceName)
On Error Resume Next

Dim sNamespace, sQuery, oWMI, objClasses, sState
sNamespace = "winmgmts://" &amp; sTargetComputer &amp; "/root/cimv2"
sQuery = "SELECT State FROM Win32_Service where Name = """ &amp; EscapeWQLString(sServiceName) &amp; """"

Set oWMI = GetObject(sNamespace)
Set objClasses = oWMI.ExecQuery(sQuery)

if objClasses.Count &gt;= 1 Then
sState = GetFirstItemFromWMIQuery(objClasses).Properties_.Item("State")
End If

If Err.number &lt;&gt; 0 Or objClasses.Count = 0 Then
sState = "Unknown"
End If

Err.Clear
GetServiceState = sState
End Function
'#Include File:Error.vbs

Class Error
Private m_lNumber
Private m_sSource
Private m_sDescription
Private m_sHelpContext
Private m_sHelpFile

Public Sub Save()
m_lNumber = Err.Number
m_sSource = Err.Source
m_sDescription = Err.Description
m_sHelpContext = Err.HelpContext
m_sHelpFile = Err.HelpFile
End Sub

Public Sub Raise()
Err.Raise m_lNumber, m_sSource, m_sDescription, m_sHelpFile, m_sHelpContext
End Sub

Public Sub Clear()
m_lNumber = 0
m_sSource = ""
m_sDescription = ""
m_sHelpContext = ""
m_sHelpFile = ""
End Sub

Public Default Property Get Number()
Number = m_lNumber
End Property
Public Property Get Source()
Source = m_sSource
End Property
Public Property Get Description()
Description = m_sDescription
End Property
Public Property Get HelpContext()
HelpContext = m_sHelpContext
End Property
Public Property Get HelpFile()
HelpFile = m_sHelpFile
End Property
End Class

Function ThrowScriptErrorNoAbort(ByVal sMessage, ByVal oErr)
On Error Resume Next
Dim oAPITemp
Set oAPITemp = MOMCreateObject("MOM.ScriptAPI")
oAPITemp.LogScriptEvent WScript.ScriptName, 4001, 1, sMessage &amp; ". " &amp; oErr.Description
End Function

Function ThrowScriptError(Byval sMessage, ByVal oErr)
On Error Resume Next
ThrowScriptErrorNoAbort sMessage, oErr
Quit()
End Function

Sub HandleError(customMessage)
Dim localLogger
If Not (Err.number = 0) Then
Set localLogger = new ScriptLogger
localLogger.LogFormattedError(customMessage)
Wscript.Quit 0
End If
End Sub

Function HandleErrorContinue(customMessage)
Dim localLogger
HandleErrorContinue = False
If Not (Err.number = 0) Then
Set localLogger = new ScriptLogger
localLogger.LogFormattedError(customMessage)
Err.Clear
HandleErrorContinue = True
End If
End Function

'#Include File:WMI.vbs

Function EscapeWQLString (ByVal strValue)
On Error Resume Next
Err.Clear
EscapeWQLString = Replace(strValue, "'", "\'")
End Function

Function WMIGetProperty(oWmi, sPropName, nCIMType, ErrAction)
Dim sValue, oWmiProp

If Not IsValidObject(oWmi) Then
If (ErrAction And ErrAction_ThrowError) = ErrAction_ThrowError Then _
ThrowScriptErrorNoAbort "Accessing property on invalid WMI object.", Err

If (ErrAction And ErrAction_Abort) = ErrAction_Abort Then _
Quit()

WMIGetProperty = ""
Exit Function
End If

On Error Resume Next
Set oWmiProp = oWmi.Properties_.Item(sPropName)
If Err.Number &lt;&gt; 0 Then
If (ErrAction And ErrAction_ThrowError) = ErrAction_ThrowError Then _
ThrowScriptErrorNoAbort "An error occurred while accessing WMI property: '" &amp; sPropName &amp; "'.", Err

If (ErrAction And ErrAction_Abort) = ErrAction_Abort Then _
Quit()
End If
On Error GoTo 0

If IsValidObject(oWmiProp) Then
sValue = oWmiProp.Value

If IsNull(sValue) Then
'
' If value is null, return blank to avoid any issues
'
WMIGetProperty = ""

Else

Select Case (oWmiProp.CIMType)
Case wbemCimtypeString, wbemCimtypeSint16, wbemCimtypeSint32, wbemCimtypeReal32, wbemCimtypeReal64, wbemCimtypeSint8, wbemCimtypeUint8, wbemCimtypeUint16, wbemCimtypeUint32, wbemCimtypeSint64, wbemCimtypeUint64:
If Not oWmiProp.IsArray Then
WMIGetProperty = Trim(CStr(sValue))
Else
WMIGetProperty = Join(sValue, ", ")
End If

Case wbemCimtypeBoolean:
If sValue = 1 Or UCase(sValue) = "TRUE" Then
WMIGetProperty = "True"
Else
WMIGetProperty = "False"
End If

Case wbemCimtypeDatetime:
Dim sTmpStrDate

'
' First attempt to convert the whole wmi date string
'
sTmpStrDate = Mid(sValue, 5, 2) &amp; "/" &amp; _
Mid(sValue, 7, 2) &amp; "/" &amp; _
Left(sValue, 4) &amp; " " &amp; _
Mid (sValue, 9, 2) &amp; ":" &amp; _
Mid(sValue, 11, 2) &amp; ":" &amp; _
Mid(sValue, 13, 2)
If IsDate(sTmpStrDate) Then
WMIGetProperty = CDate(sTmpStrDate)
Else

'
' Second, attempt just to convert the YYYYMMDD
'
sTmpStrDate = Mid(sValue, 5, 2) &amp; "/" &amp; _
Mid(sValue, 7, 2) &amp; "/" &amp; _
Left(sValue, 4)
If IsDate(sTmpStrDate) Then
WMIGetProperty = CDate(sTmpStrDate)
Else
'
' Nothing works - return passed in string
'
WMIGetProperty = sValue
End If

End If

Case Else:
WMIGetProperty = ""
End Select
End If
Else

If (ErrAction And ErrAction_ThrowError) = ErrAction_ThrowError Then _
ThrowScriptErrorNoAbort "An error occurred while accessing WMI property: '" &amp; sPropName &amp; "'.", Err

If (ErrAction And ErrAction_Abort) = ErrAction_Abort Then _
Quit()

WMIGetProperty = ""

End If


If (ErrAction And ErrAction_Trace) = ErrAction_Trace Then _
WScript.Echo " + " &amp; sPropName &amp; " :: '" &amp; WMIGetProperty &amp; "'"

End Function

Function WMIExecQuery(ByVal sNamespace, ByVal sQuery)
'
' WMIExecQuery :: Executes the WMI query and returns the result set.
'
'
Dim oWMI, oQuery, nInstanceCount
Dim e
Set e = New Error
On Error Resume Next
Set oWMI = GetObject(sNamespace)
e.Save
On Error GoTo 0
If IsEmpty(oWMI) Then
ThrowScriptErrorNoAbort "Unable to open WMI Namespace '" &amp; sNamespace &amp; "'. Check to see if the WMI service is enabled and running, and ensure this WMI namespace exists.", e
ThrowEmptyDiscoveryData
End If

On Error Resume Next
Set oQuery = oWMI.ExecQuery(sQuery)
e.Save
On Error GoTo 0
If IsEmpty(oQuery) Or e.Number &lt;&gt; 0 Then
ThrowScriptError "The Query '" &amp; sQuery &amp; "' returned an invalid result set. Please check to see if this is a valid WMI Query.", e
End If

'Determine if we queried a valid WMI class - Count will return 0 or empty
On Error Resume Next
nInstanceCount = oQuery.Count
e.Save
On Error GoTo 0
If e.Number &lt;&gt; 0 Then
ThrowScriptError "The Query '" &amp; sQuery &amp; "' did not return any valid instances. Please check to see if this is a valid WMI Query.", e
End If

Set WMIExecQuery = oQuery

End Function

Function GetFirstItemFromWMIQuery(ByRef oQuery)
ON ERROR RESUME NEXT
Err.Clear
Dim oResult
Set oResult = oQuery.ItemIndex(0)
if Err.number &lt;&gt; 0 then
Err.Clear
Dim oObject
For Each oObject in oQuery
Set oResult = oObject
Exit For
Next
end if
Set GetFirstItemFromWMIQuery = oResult
End Function
'#Include File:ConnectionString.vbs

Function BuildConnectionString(strServer, strDatabase)
ON ERROR RESUME NEXT
Err.Clear

Dim dataSource
dataSource = BuildServerName(strServer, "")
BuildConnectionString = "Data Source=" &amp; EscapeConnStringValue(dataSource) &amp; ";Initial Catalog=" &amp; EscapeConnStringValue(strDatabase) &amp; ";Integrated Security=SSPI"
End Function

Function BuildConnectionStringWithPort(ByVal strServer, ByVal strDatabase, ByVal tcpPort)
ON ERROR RESUME NEXT
Err.Clear

Dim dataSource
dataSource = strServer
If ((tcpPort &lt;&gt; "0") And (tcpPort &lt;&gt; "")) Then
dataSource = dataSource &amp; "," &amp; tcpPort
End If
BuildConnectionStringWithPort = "Data Source=" &amp; EscapeConnStringValue(dataSource) &amp; ";Initial Catalog=" &amp; EscapeConnStringValue(strDatabase) &amp; ";Integrated Security=SSPI"
End Function

' This function should be used to escape Connection String keywords.
Function EscapeConnStringValue (ByVal strValue)
ON ERROR RESUME NEXT
Err.Clear

EscapeConnStringValue = """" + Replace(strValue, """", """""") + """"
End Function

Function EscapeWQLString (ByVal strValue)
ON ERROR RESUME NEXT
Err.Clear

EscapeWQLString = Replace(strValue, "'", "\'")
End Function

Function GetTcpPort (ByVal strServer)
ON ERROR RESUME NEXT
Err.Clear

Dim tcpPort
tcpPort = ""

Call BuildServerName(strServer, tcpPort)

GetTcpPort = tcpPort

End Function

Function BuildServerName(ByVal strServer, ByRef tcp)
ON ERROR RESUME NEXT
Err.Clear

Dim pathArray, instanceName, computerName, ip, serverName
Dim oWMI, oQuery

ip= ""

pathArray = Split(strServer, "\")
computerName = pathArray(0)
instanceName = "MSSQLSERVER"
if (pathArray.Count &gt; 1) Then
instanceName = pathArray(1)
End If

serverName = strServer

Set oWMI = GetObject("winmgmts:\\" &amp; computerName &amp; "\root\Microsoft\SqlServer\" &amp; SQL_WMI_NAMESPACE)
Set oQuery = oWMI.ExecQuery("SELECT * FROM ServerNetworkProtocolProperty WHERE ProtocolName = 'Tcp' AND InstanceName = '"&amp; EscapeWQLString(instanceName) &amp;"' AND PropertyName = 'ListenOnAllIPs'")

If oQuery.Count &gt;0 Then
Dim isListenAll
Set isListenAll = GetFirstItemFromWMIQuery(oQuery)
If(isListenAll.PropertyNumVal = 1) Then
Set oQuery = oWMI.ExecQuery("SELECT * FROM ServerNetworkProtocolProperty WHERE ProtocolName = 'Tcp' AND InstanceName = '"&amp; EscapeWQLString(instanceName) &amp;"' AND IPAddressName = 'IPAll' AND (PropertyName = 'TcpPort' OR PropertyName = 'TcpDynamicPorts') AND PropertyStrVal &lt;&gt; ''")

If (oQuery.Count &gt; 0) Then
tcp = GetFirstItemFromWMIQuery(oQuery).PropertyStrVal

If ((tcp &lt;&gt; "0") And (tcp &lt;&gt; "")) Then
serverName = serverName &amp; "," &amp; tcp
Else tcp = ""
End If
End If
Else
Set oQuery = oWMI.ExecQuery("SELECT * FROM ServerNetworkProtocolProperty WHERE ProtocolName = 'Tcp' AND InstanceName = '"&amp; EscapeWQLString(instanceName) &amp;"' AND IPAddressName &lt;&gt; '' AND PropertyName = 'Enabled' AND PropertyNumVal = 1")
If (oQuery.Count &gt; 0) Then
Dim ipAddressName
ipAddressName = GetFirstItemFromWMIQuery(oQuery).IPAddressName
Set oQuery = oWMI.ExecQuery("SELECT * FROM ServerNetworkProtocolProperty WHERE ProtocolName = 'Tcp' AND InstanceName = '"&amp; EscapeWQLString(instanceName) &amp;"' AND IPAddressName = '"&amp; EscapeWQLString(ipAddressName) &amp;"' AND (PropertyName = 'TcpPort' OR PropertyName = 'TcpDynamicPorts') AND PropertyStrVal &lt;&gt; ''")
If (oQuery.Count &gt; 0) Then
tcp = GetFirstItemFromWMIQuery(oQuery).PropertyStrVal
End If
Set oQuery = oWMI.ExecQuery("SELECT * FROM ServerNetworkProtocolProperty WHERE ProtocolName = 'Tcp' AND InstanceName = '"&amp; EscapeWQLString(instanceName) &amp;"' AND IPAddressName = '"&amp; EscapeWQLString(ipAddressName) &amp;"' AND PropertyName = 'IpAddress' AND PropertyStrVal &lt;&gt; ''")
If (oQuery.Count &gt; 0) Then
ip = GetFirstItemFromWMIQuery(oQuery).PropertyStrVal
End If
If ip &lt;&gt; "" Then
serverName = ip
End If
If ((tcp &lt;&gt; "0") And (tcp &lt;&gt; "")) Then
serverName = servername &amp; "," &amp; tcp
Else tcp = ""
End If
End If
End If
End If
On Error Goto 0
BuildServerName = serverName
End Function

Public Function IsValidDestination(dbConnection, serverName, instanceName, isADODB)
Dim destinationTestQuery
destinationTestQuery = "select SERVERPROPERTY('MachineName') as ServerName, @@servicename as InstanceName"
if 0 = Err.number then
Dim queryResult
if isADODB then
Set queryResult = dbConnection.ExecuteQuery(destinationTestQuery)
else
Set queryResult = dbConnection.Execute(destinationTestQuery)
end if
if Not queryResult.EOF then
Dim queryServerName : queryServerName = UCase(queryResult("ServerName").Value)
Dim queryInstanceName : queryInstanceName = UCase(queryResult("InstanceName").Value)
Dim serverNameWithoutDomain : serverNameWithoutDomain = serverName
Dim dotPosition : dotPosition = InStr(1, serverName, ".")
if Not IsNull(dotPosition) And (dotPosition &gt; 0) then
serverNameWithoutDomain = Left(serverName, dotPosition - 1)
end if
if (UCase(serverNameWithoutDomain) = queryServerName) And (UCase(instanceName) = queryInstanceName) then
IsValidDestination = true
Exit Function
end if
end if
end if
IsValidDestination = false
End Function

'NOTE: This will NOT work without SQLADODB.vbs /DKalinin/
'RETURNS:
Public Function SmartConnect(cnADOConnection, connectionStr, tcp, serverName, instanceName, databaseName)
ON ERROR RESUME NEXT
'try to use SQL server browser
Dim strProv : strProv = BuildConnectionStringWithPort(connectionStr, databaseName, "")
Err.Clear
Dim res : res = cnADOConnection.Open(strProv, "sqloledb", 10)
'use original tcp port and try to connect again
if (0 &lt;&gt; Err.number) Or (Not IsValidDestination(cnADOConnection, serverName, instanceName, true)) then
strProv = BuildConnectionStringWithPort(connectionStr, databaseName, tcp)
Err.Clear
res = cnADOConnection.Open(strProv, "sqloledb", 10)
'get fresh tcp port and try to connect again
if (0 &lt;&gt; Err.number) Or (Not IsValidDestination(cnADOConnection, serverName, instanceName, true)) then
Err.Clear
strProv = BuildConnectionString(connectionStr, databaseName)
res = cnADOConnection.Open(strProv, "sqloledb", 30)

if (0 &lt;&gt; Err.number) Or (Not IsValidDestination(cnADOConnection, serverName, instanceName, true)) then
cnADOConnection.HandleOpenConnectionErrorContinue databaseName, serverName, instanceName
SmartConnect = False
Exit Function
end if
end if
end if
SmartConnect = res
End Function


'NOTE: This WILL work without SQLADODB.vbs /DKalinin/
Public Function SmartConnectWithoutSQLADODB(connectionStr, tcp, serverName, instanceName, databaseName)
ON ERROR RESUME NEXT
Dim cnADOConnection
Set cnADOConnection = MomCreateObject("ADODB.Connection")
cnADOConnection.Provider = "sqloledb"
cnADOConnection.ConnectionTimeout = 30
'try to use SQL server browser
Dim strProv : strProv = BuildConnectionStringWithPort(connectionStr, databaseName, "")
Err.Clear
cnADOConnection.Open strProv
'use original tcp port and try to connect again
if (0 &lt;&gt; Err.number) Or (Not IsValidDestination(cnADOConnection, serverName, instanceName, false)) then
Err.Clear
strProv = BuildConnectionStringWithPort(connectionStr, databaseName, tcp)
cnADOConnection.Open strProv
'get fresh tcp port and try to connect again
if (0 &lt;&gt; Err.number) Or (Not IsValidDestination(cnADOConnection, serverName, instanceName, false)) then
Err.Clear
strProv = BuildConnectionString(connectionStr, databaseName)
cnADOConnection.Open strProv

if (0 &lt;&gt; Err.number) Or (Not IsValidDestination(cnADOConnection, serverName, instanceName, false)) then
cnADOConnection.HandleOpenConnectionErrorContinue databaseName, serverName, instanceName
Set SmartConnectWithoutSQLADODB = Nothing
Exit Function
end if
end if
end if
Set SmartConnectWithoutSQLADODB = cnADOConnection
End Function

Function furlEncode(vString,vEncDec)
Dim i
Dim aReserved(24,1)
'column 1
aReserved(0,0) = "%" '25
aReserved(1,0) = ";" '3B
aReserved(2,0) = "/" '2F
aReserved(3,0) = "?" '3F
aReserved(4,0) = ":" '3A
aReserved(5,0) = "@" '40
aReserved(6,0) = "&amp;" '26
aReserved(7,0) = "=" '3D
aReserved(8,0) = "+" '2B
aReserved(9,0) = "$" '24
aReserved(10,0) = "," '2C
aReserved(11,0) = " " '20
aReserved(12,0) = """" '22
aReserved(13,0) = "&lt;" '3C
aReserved(14,0) = "&gt;" '3E
aReserved(15,0) = "#" '23
aReserved(16,0) = "{" '7B
aReserved(17,0) = "}" '7D
aReserved(18,0) = "|" '7C
aReserved(19,0) = "\" '5C
aReserved(20,0) = "^" '5E
aReserved(21,0) = "~" '7E
aReserved(22,0) = "[" '5B
aReserved(23,0) = "]" '5D
aReserved(24,0) = "`" '60
'column 2
aReserved(0,1) = "%25"
aReserved(1,1) = "%3B"
aReserved(2,1) = "%2F"
aReserved(3,1) = "%3F"
aReserved(4,1) = "%3A"
aReserved(5,1) = "%40"
aReserved(6,1) = "%26"
aReserved(7,1) = "%3D"
aReserved(8,1) = "%2B"
aReserved(9,1) = "%24"
aReserved(10,1) = "%2C"
aReserved(11,1) = "%20"
aReserved(12,1) = "%22"
aReserved(13,1) = "%3C"
aReserved(14,1) = "%3E"
aReserved(15,1) = "%23"
aReserved(16,1) = "%7B"
aReserved(17,1) = "%7D"
aReserved(18,1) = "%7C"
aReserved(19,1) = "%5C"
aReserved(20,1) = "%5E"
aReserved(21,1) = "%7E"
aReserved(22,1) = "%5B"
aReserved(23,1) = "%5D"
aReserved(24,1) = "%60"

For i = 0 to Ubound(aReserved)
If vEncDec = "enc" Then
vString = Replace(vString,aReserved(i,0),aReserved(i,1))
End If
If vEncDec = "dec" Then
vString = Replace(vString,aReserved(i,1),aReserved(i,0))
End If
Next

furlEncode = vString

End Function'#Include File:GetSQL2008AgentJobStatus.vbs
'Copyright (c) Microsoft Corporation. All rights reserved.

Const SQL_MONITORING_CONNECT_FAILURE = -1
Const SQL_MONITORING_QUERY_FAILURE = -2
Const SQL_MONITORING_SUCCESS = 0

Dim SCRIPT_SQL

SCRIPT_SQL = "SET NOCOUNT ON" &amp; VbCrLf &amp;_
"DECLARE @job_activity TABLE (" &amp; VbCrLf &amp;_
"[session_id] [int] NOT NULL," &amp; VbCrLf &amp;_
"[job_id] [uniqueidentifier] NOT NULL," &amp; VbCrLf &amp;_
"[job_name] [sysname] COLLATE SQL_Latin1_General_CP1_CS_AS NOT NULL," &amp; VbCrLf &amp;_
"[run_requested_date] [datetime] NULL," &amp; VbCrLf &amp;_
"[run_requested_source] [sysname] COLLATE SQL_Latin1_General_CP1_CS_AS NULL," &amp; VbCrLf &amp;_
"[queued_date] [datetime] NULL," &amp; VbCrLf &amp;_
"[start_execution_date] [datetime] NULL," &amp; VbCrLf &amp;_
"[last_executed_step_id] [int] NULL," &amp; VbCrLf &amp;_
"[last_exectued_step_date] [datetime] NULL," &amp; VbCrLf &amp;_
"[stop_execution_date] [datetime] NULL," &amp; VbCrLf &amp;_
"[next_scheduled_run_date] [datetime] NULL," &amp; VbCrLf &amp;_
"[job_history_id] [int] NULL," &amp; VbCrLf &amp;_
"[message] [nvarchar](1024) COLLATE SQL_Latin1_General_CP1_CS_AS NULL," &amp; VbCrLf &amp;_
"[run_status] [int] NULL," &amp; VbCrLf &amp;_
"[operator_id_emailed] [int] NULL," &amp; VbCrLf &amp;_
"[operator_id_netsent] [int] NULL," &amp; VbCrLf &amp;_
"[operator_id_paged] [int] NULL," &amp; VbCrLf &amp;_
"[execution_time_minutes] [int] NULL )" &amp; VbCrLf &amp;_
"INSERT INTO @job_activity" &amp; VbCrLf &amp;_
"([session_id]" &amp; VbCrLf &amp;_
",[job_id]" &amp; VbCrLf &amp;_
",[job_name]" &amp; VbCrLf &amp;_
",[run_requested_date]" &amp; VbCrLf &amp;_
",[run_requested_source]" &amp; VbCrLf &amp;_
",[queued_date]" &amp; VbCrLf &amp;_
",[start_execution_date]" &amp; VbCrLf &amp;_
",[last_executed_step_id]" &amp; VbCrLf &amp;_
",[last_exectued_step_date]" &amp; VbCrLf &amp;_
",[stop_execution_date]" &amp; VbCrLf &amp;_
",[next_scheduled_run_date]" &amp; VbCrLf &amp;_
",[job_history_id]" &amp; VbCrLf &amp;_
",[message]" &amp; VbCrLf &amp;_
",[run_status]" &amp; VbCrLf &amp;_
",[operator_id_emailed]" &amp; VbCrLf &amp;_
",[operator_id_netsent]" &amp; VbCrLf &amp;_
",[operator_id_paged])" &amp; VbCrLf &amp;_
"EXECUTE [msdb].[dbo].[sp_help_jobactivity]" &amp; VbCrLf &amp;_
"SELECT" &amp; VbCrLf &amp;_
"[ja].[job_id]" &amp; VbCrLf &amp;_
",[ja].[job_name]" &amp; VbCrLf &amp;_
",[originating_server]" &amp; VbCrLf &amp;_
",[message]" &amp; VbCrLf &amp;_
",[run_status]" &amp; VbCrLf &amp;_
", [execution_time_minutes] = case" &amp; VbCrLf &amp;_
" -- Has not finished a run" &amp; VbCrLf &amp;_
" When [start_execution_date] is not null And [stop_execution_date] is null" &amp; VbCrLf &amp;_
" Then DATEDIFF(minute, [start_execution_date], GETDATE())" &amp; VbCrLf &amp;_
" -- Has finished that run, but we still need to time for monitor state" &amp; VbCrLf &amp;_
" When [start_execution_date] is not null and [stop_execution_date] is not null" &amp; VbCrLf &amp;_
" Then DATEDIFF(minute, [start_execution_date], [stop_execution_date])" &amp; VbCrLf &amp;_
" else null" &amp; VbCrLf &amp;_
"End" &amp; VbCrLf &amp;_
" " &amp; VbCrLf &amp;_
"FROM @job_activity [ja]" &amp; VbCrLf &amp;_
"JOIN [msdb].[dbo].[sysjobs_view] [sjv] ON [sjv].[job_id] = [ja].[job_id]"



'Start of Main
'-----------------------------------------------------------------------------------------------
call Main()

Sub Main()

Dim objParameters, sConnectionString, sTcpPort, Computer, Service, InstanceName
Dim oAPI, oBag

Set objParameters = WScript.Arguments

If objParameters.Count &lt;&gt; 5 Then
Quit()
End If

sConnectionString= objParameters(0)
sTcpPort = objParameters(1)
Computer = objParameters(2)
Service = objParameters(3)
InstanceName = objParameters(4)

Set objParameters = Nothing

Set oAPI = MOMCreateObject("MOM.ScriptAPI")
Set oBag = oAPI.CreatePropertyBag()

Dim state
state = GetServiceState(Computer, Service)
if (state &lt;&gt; "Running") And (state &lt;&gt; "Unknown") Then
Call oAPI.Return(oBag)
Quit()
End If

If GetJobStatus(oBag, sConnectionString, sTcpPort, Computer, InstanceName) = 0 Then
Call oAPI.Return(oBag)
Else
Call oAPI.Return(oBag)
Quit()
End If

End Sub
'End of Main

'-----------------------------------------------------------------------------------------------
'The function returns service or "Unknown" state
'Input:
' server - compute name
' service - system service name
'Output:
' service state or "Unknown" state
Function GetServiceState( sTargetComputer, sServiceName)
On Error Resume Next

Dim sNamespace, sQuery, oWMI, objClasses, sState
sNamespace = "winmgmts://" &amp; sTargetComputer &amp; "/root/cimv2"
sQuery = "SELECT State FROM Win32_Service where Name = """ &amp; EscapeWQLString(sServiceName) &amp; """"

Set oWMI = GetObject(sNamespace)
Set objClasses = oWMI.ExecQuery(sQuery)

if objClasses.Count &gt;= 1 Then
sState = GetFirstItemFromWMIQuery(objClasses).Properties_.Item("State")
End If

If Err.number &lt;&gt; 0 Or objClasses.Count = 0 Then
sState = "Unknown"
End If

Err.Clear
GetServiceState = sState
End Function
'End of Main
'-----------------------------------------------------------------------------------------------

Function GetJobStatus (ByRef oBag, ByVal sConnectionString, ByVal sTcpPort, ByVal Computer, ByVal InstanceName)


Dim cnADOConnection
Dim rsSQLJobs
Dim bFail
Dim nDuration
Dim jobID
Dim lastStatus
Dim lastMessage


'on error resume next

Set cnADOConnection = SmartConnectWithoutSQLADODB(sConnectionString, sTcpPort, Computer, InstanceName, "msdb")
if cnADOConnection Is Nothing Then
GetJobStatus = SQL_MONITORING_CONNECT_FAILURE
Exit Function
End If

Err.Clear
Set rsSQLJobs = cnADOConnection.Execute(SCRIPT_SQL)
If 0 &lt;&gt; Err.number Then
GetJobStatus = SQL_MONITORING_QUERY_FAILURE
Exit Function
End If

If 0 = rsSQLJobs.State Then
' No records returned, recordset is likely closed.
Exit Function
End If

Do
bFail = True
Err.Clear
if rsSQLJobs.EOF then
if 0 &lt;&gt; Err.number then Exit Do
bFail = False
Exit Do
End If
If 0 &lt;&gt; Err.number Then Exit Do
jobID = rsSQLJobs("job_id").Value
lastStatus = rsSQLJobs("run_status").Value
lastMessage = rsSQLJobs("message").Value
nDuration = Int(rsSQLJobs("execution_time_minutes").Value)
If (IsNull(nDuration)) Then nDuration = -1
If (IsNull(lastStatus)) Then lastStatus = -1
If (IsNull(lastMessage)) Then lastMessage = ""
Call oBag.AddValue(jobID &amp; "-Duration",CDbl(nDuration))
Call oBag.AddValue(jobID &amp; "-LastStatus", CInt(lastStatus))
Call oBag.AddValue(jobID &amp; "-LastMessage", CStr(lastMessage))

Err.Clear
rsSQLJobs.MoveNext
If 0 &lt;&gt; Err.number then Exit Do
Loop



If bFail Then
' Throw
End if

Set cnADOConnection = Nothing
Set rsSQLJobs = Nothing


GetJobStatus = SQL_MONITORING_SUCCESS

End Function</Script></ScriptBody>
<TimeoutSeconds>$Config/TimeoutSeconds$</TimeoutSeconds>
</DataSource>
</MemberModules>
<Composition>
<Node ID="DS"/>
</Composition>
</Composite>
</ModuleImplementation>
<OutputType>System!System.PropertyBagData</OutputType>
</DataSourceModuleType>