Back to Home

Working with alerts in System Center Operations Manager using your connector

system center operations manager · powershell · monitoring · microsoft

Working with alerts in System Center Operations Manager using your connector

This article is for people who are familiar with the System Center Operations Manager product.

Terminology:
SCOM - instead of the full name;
An alert is the same as alert. There is simply no good analogue in Russian.

Introduction

In SCOM, unlike many other monitoring systems, an alert is an independent object. Depending on the settings, the check may already be green, but the alert will remain active. Alerts are used and processed:
  • operator (person)
  • standard connectors (e.g. Command Channel)
  • external connectors (for example, a connector for synchronization with the Service Desk system)

The presence of the Command Channel already gives ample opportunities for working with alerts, but this approach is, firstly, not very beautiful, and secondly, not the best in performance. Therefore, let's create our own external connector, which sends letters to emerged alerts. Yes, there is a standard for this, however, during the course of the story it will become clear that the functionality of our connector is practically unlimited. For the impatient: the script lies entirely here .

To create the connector, we use Powershell. Because:
  • it's easier than in C #
  • such a script is easier to maintain / modify

The SCOM SDK libraries will also be used. They are usually located in C: \ Program Files \ Microsoft System Center 2012 R2 \ Operations Manager \ Server \ SDK Binaries on any SCOM server.

Connector Installation

First of all, you need to create an external connector, for this we also use a script . I will not disassemble it in detail, since we will use the same objects in the main script. The main part in it:

$connectorGuid = New-Object Guid("{6A1F8C0E-B8F1-4147-8C9B-5A2F98F10007}");
if ($action -eq "InstallConnector")
{
	# подключение к SCOM
    $mg = New-Object Microsoft.EnterpriseManagement.ManagementGroup($ManagementServer);
    $icfm = $mg.ConnectorFramework;
    $info = New-Object Microsoft.EnterpriseManagement.ConnectorFramework.ConnectorInfo;
    $info.Description = "...";
    $info.DisplayName = $ConnectorName;
    $info.Name = $ConnectorName;
    $connector = $icfm.Setup($info, $connectorGuid);
    $connector.Initialize();
}

We choose an arbitrary GUID, the main thing is to use the same one in the main connector script. By the way, you can remove the connector by the script from the link.

Important. Once created, the connector will be available in the SCOM graphical console. There you can configure subscription to alerts - the procedure is almost the same as for standard connectors. If this is not done, alerts will not be sent to your connector.

Connector logic

Let's do the main script. Let's start by defining configuration parameters:

# здесь я определяю путь с скрипту, так как там же будут библиотеки
$ScriptPath = $MyInvocation.MyCommand.Path -replace $MyInvocation.MyCommand.Name;
# имя одного из ваших серверов SCOM
$ManagementServer = "scom.contoso.com";
# GUID вашего коннектора, который вы установочным скриптом
$strGuid = "{6A1F8C0E-B8F1-4147-8C9B-5A2F98F10007}";
# email адреса для нотификаций
$emailTo = '[email protected]';
$emailFrom = '[email protected]';
# smtp server организации
$Smtp = 'mail.contoso.com';

Change email addresses and server addresses according to your organization’s infrastructure.

# загружаем библиотеки SDK, которые лежат в той же папке что и скрипт
$DLLs = ("Microsoft.EnterpriseManagement.Core.dll","Microsoft.EnterpriseManagement.OperationsManager.dll","Microsoft.EnterpriseManagement.Runtime.dll");
foreach ($lib in $DLLs)
{
    [Reflection.Assembly]::LoadFile($ScriptPath + $lib) | Out-Null
}

Using these libraries, we will be able to create SCOM system objects, thereby working with it. Further:

try
{
    # подключаемся к коннектору
    $mg = New-Object Microsoft.EnterpriseManagement.ManagementGroup($ManagementServer);
    $icfm = $mg.ConnectorFramework;
    $connectorGuid = New-Object Guid($strGuid);
    $connector = $icfm.GetConnector($connectorGuid);
    # получаем все новые алерты
    $alerts = $connector.GetMonitoringAlerts();
}
catch
{
    Write-Host $_.Exception.Message.ToString();
    exit 2;
}
# помечаем алерты как обработанные
$connector.AcknowledgeMonitoringAlerts($alerts);

An alert marked in this way will not get into our connector anymore until it is modified - it is either a change in status or a change in attribute. Further:

foreach ($alert in $alerts)
{
    try
    {
        # здесь главное действие над алертом, в нашем случае, отправка письма
        $alertContext = [xml]$alert.Context;
        $alertResolutionStateName = @{0="New";255="Closed"};
		# контекст алерта это обычная xml, поэтому можно использовать XPATH
        $monitorClass = $alertContext.SelectNodes("//Property[@Name='__CLASS']/text()").Value;
        $subject = "This is an alert message from SCOM";
        $emailBody = "`n" + $alertResolutionStateName[[int]$alert.ResolutionState] + "`n" + $alert.MonitoringObjectFullName + "`n" + $alert.TimeRaised + "`n" + $monitorClass;       
		# отправляем сформированное сообщение
        Send-MailMessage -SmtpServer $Smtp -Subject $subject -From $emailFrom -To $emailTo -Body $emailBody
		# здесь можем изменить алерт
        #$alert.CustomField1 = "Notification sent.";
        #$alert.Update();
    }
    catch
    {
        Write-Host $_.Exception.Message.ToString();
    }
}

Thus, we sent a message to each alert in SCOM. Not impressive, right? However, pay attention to the last 3 lines in the try block. Indeed, in this way, you can write any information into the alert attributes or even close it (i.e. set the status to Closed). This is already more interesting. True, there is one point: if you change the alert in this way, the next time you run the script, it will again fall into the connector (as it has changed) and you can get endless processing. Therefore, before modification, an alert should be checked for the corresponding condition. In our example, you can verify that the CustomField1 attribute is empty, otherwise, do not make a modification.

So, in general, our connector is ready. A single script run processes all alerts available at that moment. For continuous operation, you can run it in an endless loop or configure regular execution in the Task Scheduler. This is much easier than maintaining a service written in C #.

Areas of use

Option one. Your organization has a Service Desk system. There is an API to it and you are familiar with it. Using this connector, you can configure the integration between SCOM and your system. If desired, it can be two-sided: when closing the ticket, close the alert.
Option Two. In your organization, infrastructure is divided into areas of responsibility. For example, lists of equipment and systems and lists of responsible are consolidated in one document. Using such a connector and this document, you can update alert attributes with certain information. Thus, it will be easier for the operator to correctly process it.

That's all, thanks for your attention.

Read Next