SQL Server Agent Job Discovery

Microsoft.SQLServer.2012.AgentJobDiscovery (DataSourceModuleType)

This module type is used to discover instances of SQL Server Agent Job

Element properties:

TypeDataSourceModuleType
IsolationAny
AccessibilityInternal
RunAsMicrosoft.SQLServer.SQLDiscoveryAccount
OutputTypeSystem.Discovery.Data

Member Modules:

ID Module Type TypeId RunAs 
DS DataSource Microsoft.Windows.TimedScript.DiscoveryProvider 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.2012.AgentJobDiscovery" Accessibility="Internal" RunAs="SQL!Microsoft.SQLServer.SQLDiscoveryAccount">
<Configuration>
<xsd:element name="IntervalSeconds" type="xsd:integer"/>
<xsd:element name="SyncTime" type="xsd:string"/>
<xsd:element name="ComputerID" type="xsd:string"/>
<xsd:element name="ComputerName" type="xsd:string"/>
<xsd:element name="SQLConnectionString" type="xsd:string"/>
<xsd:element name="SQLInstanceName" type="xsd:string"/>
<xsd:element name="ServiceName" type="xsd:string"/>
<xsd:element 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.DiscoveryProvider">
<IntervalSeconds>$Config/IntervalSeconds$</IntervalSeconds>
<SyncTime>$Config/SyncTime$</SyncTime>
<ScriptName>SQLAgentJobDiscovery.vbs</ScriptName>
<Arguments>$MPElement$ $Target/Id$ $Config/ComputerID$ $Config/ComputerName$ $Config/SQLConnectionString$ $Config/SQLInstanceName$ $Config/ServiceName$"</Arguments>
<ScriptBody><Script>
' ##### ..\Scripts\Common\Initialize.vbs
Option Explicit
SetLocale("en-us")

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
' ##### Scripts\SQL2012Constants.vbs
Const SQL_VERSION = "2012"
Const SQL_VERSION_NUMBER = "11"
Const SQL_WMI_NAMESPACE = "ComputerManagement11"

Const SQL_FULLTEXTSEARCH_SERVICENAME = "MSSQLFDLauncher"
Const SQL_FULLTEXTSEARCH_SERVICECLUSTERNAME = "SQL Full-text Filter Daemon Launcher"

Const SQL_DBENGINE_CLASS = "$MPElement[Name='Microsoft.SQLServer.2012.DBEngine']$"
Const SQL_DATABASE_CLASS = "$MPElement[Name='Microsoft.SQLServer.2012.Database']$"
Const SQL_AGENTJOB_CLASS = "$MPElement[Name='Microsoft.SQLServer.2012.AgentJob']$"
Const SQL_REPLICATION_DISTRIBUTOR_CLASS = "$MPElement[Name='Microsoft.SQLServer.2012.Distributor']$"
Const SQL_DISTRIBUTOR_CONTAINS_DATABASE_RELATIONSHIP = "$MPElement[Name='Microsoft.SQLServer.2012.DistributorContainsDatabase']$"
Const SQL_REPLICATION_PUBLISHER_CLASS = "$MPElement[Name='Microsoft.SQLServer.2012.Publisher']$"
Const SQL_REPLICATION_SUBSCRIBER_CLASS = "$MPElement[Name='Microsoft.SQLServer.2012.Subscriber']$"
Const SQL_REPLICATION_PUBLICATION_CLASS = "$MPElement[Name='Microsoft.SQLServer.2012.Publication']$"
Const SQL_REPLICATION_SUBSCRIPTION_CLASS = "$MPElement[Name='Microsoft.SQLServer.2012.Subscription']$"
Const SQL_DATABASE_ERROR_USER_POLICY_CLASS = "$MPElement[Name='Microsoft.SQLServer.2012.DatabaseErrorUserPolicy']$"
Const SQL_DATABASE_WARNING_USER_POLICY_CLASS = "$MPElement[Name='Microsoft.SQLServer.2012.DatabaseWarningUserPolicy']$"
Const SQL_USERPOLICY_DEFAULT_CATEGORY_NAME = "&lt;Default&gt;"
' ##### ..\Scripts\Common\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


' ##### ..\Scripts\Common\Discovery\SQLAgentJobDiscovery.vbs
'Copyright (c) Microsoft Corporation. All rights reserved.
' Parameters that should be passed to this script
' Parameters that should be passed to this script
' 0 MPElement ID ($MPElement$)
' 1 Target Id for ME this rule is running against ($Target/Id$)
' 2 Computer ID
' 3 Computer FQDN
' 4 SQL Connection String for the instance that the Jobs are being discovered on
' 5 SQL Instance that this rule is being run for
' 6 SQL Agent Service Name that this rule is being run for

Const SQL_DISCOVERY_CONNECT_FAILURE = -1
Const SQL_DISCOVERY_QUERY_FAILURE = -2
Const SQL_DISCOVERY_SUCCESS = 0
Const ERR_CANNOT_INSERT_NULL = 515


Dim oArgs
Set oArgs = WScript.Arguments
if oArgs.Count &lt;&gt; 7 Then
Wscript.Quit -1
End If

Dim SourceID, ManagedEntityId, TargetComputer, InstanceName, ConnectionString, TargetComputerID, ServiceName

SourceId = oArgs(0)
ManagedEntityId = oArgs(1)
TargetComputerID = oArgs(2)
TargetComputer = oArgs(3)
ConnectionString = oArgs(4)
InstanceName = oArgs(5)
ServiceName = oArgs(6)

Dim oAPI, oSQLDiscoveryData

Set oAPI = MOMCreateObject("MOM.ScriptAPI")


set oSQLDiscoveryData = oAPI.CreateDiscoveryData(0, SourceId, ManagedEntityId)

If DoJobDiscovery(ServiceName, InstanceName, ConnectionString, oSQLDiscoveryData) &gt;= 0 Then Call oAPI.Return(oSQLDiscoveryData)
WScript.Quit()

' 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 DoJobDiscovery(ByVal sServiceName, ByVal sSqlInstance, ByVal sSQLConnectionString, ByVal oDisc)

Dim e
Set e = New Error

Dim cnADOConnection
Set cnADOConnection = MomCreateObject("ADODB.Connection")
cnADOConnection.Provider = "sqloledb"
cnADOConnection.ConnectionTimeout = 30

Dim strProv
strProv = "Server=" &amp; EscapeConnStringValue(sSQLConnectionString) &amp; ";Database=msdb;Integrated Security=SSPI"

e.Clear
On Error Resume Next
cnADOConnection.Open strProv
e.Save
On Error Goto 0
if 0 &lt;&gt; Err.number then
'Error event in here
'g_oSQL.CreateConnectionFailureAlert sInstance, Err.number, Err.Description
DoDatabaseDiscovery = SQL_DISCOVERY_CONNECT_FAILURE
Exit Function
end if

Dim oResults
e.Clear
On Error Resume Next
Set oResults = cnADOConnection.Execute("sp_help_job")
e.Save
On Error Goto 0


If e.Number &lt;&gt; 0 Then
DoJobDiscovery = SQL_DISCOVERY_QUERY_FAILURE
Exit Function
End If

Dim oSQLAgentJobInstance
Dim sJobId : sJobId = ""
Dim sJobName : sJobName = ""
Dim sJobOrigin : sJobOrigin = ""
Dim sJobDescription : sJobDescription = ""
Dim sJobCategory : sJobCategory = ""
Dim sJobOwner : sJobOwner = ""

Do While Not oResults.EOF
if Not IsNull(oResults(0)) Then sJobId = oResults(0)
if Not IsNull(oResults(1)) Then sJobOrigin = oResults(1)
if Not IsNull(oResults(2)) Then sJobName = oResults(2)
if Not IsNull(oResults(4)) Then sJobDescription = oResults(4)
if Not IsNull(oResults(6)) Then sJobCategory = oResults(6)
if Not IsNull(oResults(7)) Then sJobOwner = oResults(7)

Set oSQLAgentJobInstance = oSQLDiscoveryData.CreateClassInstance(SQL_AGENTJOB_CLASS)
' Set basic Agent Job properties
With oSQLAgentJobInstance
.AddProperty "$MPElement[Name='Windows!Microsoft.Windows.Computer']/PrincipalName$", TargetComputerID
.AddProperty "$MPElement[Name='SQL!Microsoft.SQLServer.ServerRole']/InstanceName$", sSqlInstance
.AddProperty "$MPElement[Name='SQL!Microsoft.SQLServer.Agent']/ServiceName$", sServiceName
.AddProperty "$MPElement[Name='SQL!Microsoft.SQLServer.AgentJob']/JobID$", sJobId
.AddProperty "$MPElement[Name='SQL!Microsoft.SQLServer.AgentJob']/OriginatingServer$", sJobOrigin
.AddProperty "$MPElement[Name='SQL!Microsoft.SQLServer.AgentJob']/Name$", sJobName
.AddProperty "$MPElement[Name='SQL!Microsoft.SQLServer.AgentJob']/IsEnabled$", CBool(oResults(3))
.AddProperty "$MPElement[Name='SQL!Microsoft.SQLServer.AgentJob']/Description$", sJobDescription
.AddProperty "$MPElement[Name='SQL!Microsoft.SQLServer.AgentJob']/Category$", sJobCategory
.AddProperty "$MPElement[Name='SQL!Microsoft.SQLServer.AgentJob']/Owner$", sJobOwner
.AddProperty "$MPElement[Name='System!System.Entity']/DisplayName$", sJobName
End With


' Add Agent Job to the Instance List and move to next Agent Job
call oSQLDiscoveryData.AddInstance(oSQLAgentJobInstance)
oResults.MoveNext

Loop

Set oResults = nothing
cnADOConnection.Close
DoJobDiscovery = SQL_DISCOVERY_SUCCESS

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