PI Services

Le blog des collaborateurs de PI Services

SCOM - Widget Powershell Grid - Exemple pour lister les alertes de Discovery/Monitoring

Sous ce titre, le cas de l'utilisation du Widget Powershell Grid dans la console Monitoring de SCOM pour afficher certaines alertes spécifiques.

On commence par creer une vue Dashboard

 

On choisit le template Grid Layout

 

On nomme le dashboard

 

On selectionne 1 cell

 

Cliquer Create

Cliquer "Click to add widget"

Selectionner Powershell Grid Widget

 

Nommer le widget, par exemple avec le meme nom que le dashboard

 

Copier coller le script suivant dans le champ Script

# Get SCOM Alert Related to Discovery and Monitoring Error
$Alerts = Get-SCOMAlert -Criteria "ResolutionState <> 255 AND Name matches '.*(Discovery|Monitoring) (failed|error).*'" #| select name,MonitoringObjectDisplayName,MonitoringObjectPath,LastModified,Description | ft -AutoSize

foreach ($alert in $Alerts)
{

$AlertName = $alert.name

$AlertLastModified = $alert.lastmodified

$MonObjDisplayName = $alert.MonitoringObjectDisplayName.ToString()

$MonObjPath = $alert.MonitoringObjectPath.ToString()

$AlertDesc = $alert.Description.ToString()

$dataObject = $ScriptContext.CreateInstance('xsd://foo!bar/baz')

#Create an ID used for sorting the output - Must be a string value - Used to sort the grid
$dataObject['Id'] = $MonObjDisplayName
$dataObject['name'] = $AlertName
$dataObject['MonitoringPath'] = $MonObjPath
$dataObject['LastModified'] = $AlertLastModified
$dataObject['Description'] = $AlertDesc


# Add the data object to be displayed in the dashboard
  $ScriptContext.ReturnCollection.Add($dataObject)

}

 

Dans ce script on recupere les alertes dont le nom correspond a des erreur de Discovery ou Monitoring.

Ne pas hesiter a faire évoluer les critères pour inclures d'autres cas propre a votre environnement.

Get-SCOMAlert -Criteria "ResolutionState <> 255 AND Name matches '.*(Discovery|Monitoring) (failed|error).*'"

 

Cliquer Create

Cliquer Close

 

La liste des alertes s'affiche

 

 

SCOM - Script - Exemple d'inventaire avec les classes "Principales".

L'idée du script ci-dessous est de proposer une forme d'inventaire des applications couvertes par une infra SCOM, en utilisant une liste, a maintenir, des principales classes d'objets tel que  'Active Directory Domain Controller Computer Role'  ou encore 'IIS Server Role'.

Il est donc necessaire de maintenir un minimum dans le temps, le contenu de $ClassList, et la correspondance faites entre les pattern de nom de classes et les application correspondantes.

SCOM_Inventory_with_Main_Classes.ps1 (12,71 kb)

 

### SCOM INVENTORY USING APPLICATION MAIN CLASS ###


#Parameters
Param(
$MS= "MyMS.MyDomain",
$cred = $(Get-Credential "MyDomain\")
)


# List of all 'Top' Classes for which we need to get instances
$ClassList=(
# ACTIVE DIRECTORY
'Active Directory Domain Controller Computer Role',` # ACTIVE DIRECTORY
'Certificate Service',  # ACTIVE DIRECTORY CERTIFICATE SERVICES
'Federation Server',    # ACTIVE DIRECTORY FEDERATION SERVICES 

# CITRIX
'Managed Citrix Presentation Server',  # CITRIX


# EXCHANGE
'Microsoft Exchange 2010 Server', # EXCHANGE
'Exchange 2007 Server Role', # EXCHANGE
'Exchange 2013 Server', # EXCHANGE

# LYNC/SKYPE
'LS Server Role', # LYNC/SKYPE

# SHAREPOINT
'SharePoint Server', # SHAREPOINT

# SQL
'SQL Server 2008 DB Engine', # SQL (SQL 2008)
'SQL Server 2012 DB Engine', # SQL (SQL 2012)
'SQL Server 2014 DB Engine', # SQL (SQL 2014)
'SQL Server 2016 DB Engine', # SQL (SQL 2016)
'MSSQL on Windows: DB Engine', # SQL (SQL 2017+)

# SQL SSIS
'SQL Server 2014 Integration Services', # SQL SSIS (SQL 2014)
'SQL Server 2016 Integration Services', # SQL SSIS (SQL 2016)
'MSSQL on Windows Integration Services: Local Instance', # SQL SSIS (SQL 2017+)

# SQL SSAS
'SSAS 2008 Instance', # SQL SSAS (SQL 2008)
'SSAS 2012 Instance', # SQL SSAS (SQL 2012)
'SSAS 2014 Instance', # SQL SSAS (SQL 2014)
'SSAS 2016 Instance', # SQL SSAS (SQL 2016)
'MSSQL Analysis Services: Generic Instance', # SQL SSAS (SQL 2017+)

# SQL SSRS
'Microsoft SQL Server 2008 Reporting Services (Native Mode)', # SQL SSRS (SQL 2008)
'Microsoft SQL Server 2012 Reporting Services (Native Mode)', # SQL SSRS (SQL 2012)
'Microsoft SQL Server 2014 Reporting Services (Native Mode)', # SQL SSRS (SQL 2014)
'Microsoft SQL Server 2016 Reporting Services (Native Mode)', # SQL SSRS (SQL 2016)
'MSSQL Reporting Services: Instance (Native Mode)' , # SQL SSRS (SQL 2017)

# WINDOWS CLUSTER NODES
'Cluster Node', # WINDOWS CLUSTER

# IIS
'IIS Server Role', # IIS

# WINDOWS PRINT SERVER
'Print Services Role', # WINDOWS PRINT SERVER

# WINDOWS DNS
'Windows DNS Server', # WINDOWS DNS

# WSUS
'WSUS 3.0 Server', # WSUS
'Microsoft Windows Server Update Services 2012 R2', # WSUS
'Microsoft Windows Server Update Services 2016' # WSUS


  
)


#Import of SCOM module
try
{
Import-Module -Name OperationsManager -ErrorAction stop
}
catch
{
write-host -ForegroundColor red "Error during import of SCOM Module"
}

#Connection to $MS management server
New-SCOMManagementGroupConnection -ComputerName $MS -Credential $cred



# Create an empty tableau
$Finaltableau = @()


# Get All Instances for each class
foreach ($classname in $ClassList)
{

    
    $class = Get-SCOMClass -DisplayName $classname

    # If class is found we can go on  
    If($class)
    {
    


                $instances += Get-SCOMClassInstance -Class $class -ErrorAction SilentlyContinue



                foreach ($inst in $instances)
                {

                $obj = New-Object psobject


                    switch -Regex ($classname)
                    {
                    # ACTIVE DIRECTORY
                    "Active Directory Domain Controller Computer Role"  
                                            {

                                            $obj | Add-Member -Name "COMPUTER" -membertype Noteproperty -Value $inst.path
                                            $obj | Add-Member -Name "CLASS" -membertype Noteproperty -Value $classname
                                            $obj | Add-Member -Name "MAIN ROLE" -membertype Noteproperty -Value "ACTIVE DIRECTORY"
                                            }
    
    
                    # ACTIVE DIRECTORY CERTIFICATE SERVICES
                    "Certificate Service"   
                                            {
                                            $obj | Add-Member -Name "COMPUTER" -membertype Noteproperty -Value $inst.displayname
                                            $obj | Add-Member -Name "CLASS" -membertype Noteproperty -Value $classname
                                            $obj | Add-Member -Name "MAIN ROLE" -membertype Noteproperty -Value "ACTIVE DIRECTORY CERTIFICATE SERVICES"
                                            }


                    # ACTIVE DIRECTORY FEDERATION SERVICES
                    "Federation Server"   
                                            {
                                            $obj | Add-Member -Name "COMPUTER" -membertype Noteproperty -Value $inst.displayname
                                            $obj | Add-Member -Name "CLASS" -membertype Noteproperty -Value $classname
                                            $obj | Add-Member -Name "MAIN ROLE" -membertype Noteproperty -Value "ACTIVE DIRECTORY FEDERATION SERVICES"
                                            }


                    # CITRIX
                    ".*Citrix.*"   
                                            {
                                            $obj | Add-Member -Name "COMPUTER" -membertype Noteproperty -Value $inst.displayname
                                            $obj | Add-Member -Name "CLASS" -membertype Noteproperty -Value $classname
                                            $obj | Add-Member -Name "MAIN ROLE" -membertype Noteproperty -Value "CITRIX"
                                            }

                    
                    
                    # EXCHANGE
                    ".*Exchange.*"   
                                            {
                                            $obj | Add-Member -Name "COMPUTER" -membertype Noteproperty -Value $inst.displayname
                                            $obj | Add-Member -Name "CLASS" -membertype Noteproperty -Value $classname
                                            $obj | Add-Member -Name "MAIN ROLE" -membertype Noteproperty -Value "EXCHANGE"
                                            }          
                    
                    
                    # LYNC/SKYPE
                    ".*LS Server.*"   
                                            {
                                            $obj | Add-Member -Name "COMPUTER" -membertype Noteproperty -Value $inst.Path
                                            $obj | Add-Member -Name "CLASS" -membertype Noteproperty -Value $classname
                                            $obj | Add-Member -Name "MAIN ROLE" -membertype Noteproperty -Value "LYNC/SKYPE"
                                            }          



                    # SHAREPOINT
                    ".*sharepoint.*"   
                                            {
                                            $obj | Add-Member -Name "COMPUTER" -membertype Noteproperty -Value $inst.Path
                                            $obj | Add-Member -Name "CLASS" -membertype Noteproperty -Value $classname
                                            $obj | Add-Member -Name "MAIN ROLE" -membertype Noteproperty -Value "SHAREPOINT"
                                            }          




                    # SQL DB ENGINE
                    "SQL Server.*DB Engine"   
                                            {
                                            $obj | Add-Member -Name "COMPUTER" -membertype Noteproperty -Value $inst.Path
                                            $obj | Add-Member -Name "CLASS" -membertype Noteproperty -Value $classname
                                            $obj | Add-Member -Name "MAIN ROLE" -membertype Noteproperty -Value "SQL"
                                            }          



                    
                    "MSSQL on Windows: DB Engine"
   
                                            {
                                            $obj | Add-Member -Name "COMPUTER" -membertype Noteproperty -Value $inst.'[Microsoft.SQLServer.Windows.DBEngine].PrincipalName'.value
                                            $obj | Add-Member -Name "CLASS" -membertype Noteproperty -Value $classname
                                            $obj | Add-Member -Name "MAIN ROLE" -membertype Noteproperty -Value "SQL"
                                            }          





                    # SQL BI
                    ".*(SQL Server.*Integration Services|Analysis Services|Reporting Services|SSAS).*"
                       
                                            {
                                            $obj | Add-Member -Name "COMPUTER" -membertype Noteproperty -Value $inst.Path
                                            $obj | Add-Member -Name "CLASS" -membertype Noteproperty -Value $classname
                                            $obj | Add-Member -Name "MAIN ROLE" -membertype Noteproperty -Value "SQL BI"
                                            }          


                    
                    "MSSQL on Windows Integration Services: Local Instance"
                                            
                                            {
                                            $obj | Add-Member -Name "COMPUTER" -membertype Noteproperty -Value $inst.'[Microsoft.SQLServer.IS.Windows.LocalInstance].PrincipalName'.value
                                            $obj | Add-Member -Name "CLASS" -membertype Noteproperty -Value $classname
                                            $obj | Add-Member -Name "MAIN ROLE" -membertype Noteproperty -Value "SQL BI"
                                            }      






                    # WINDOWS CLUSTER
                    ".*Cluster Node.*"   
                                            {
                                            $obj | Add-Member -Name "COMPUTER" -membertype Noteproperty -Value $inst.DisplayName
                                            $obj | Add-Member -Name "CLASS" -membertype Noteproperty -Value $classname
                                            $obj | Add-Member -Name "MAIN ROLE" -membertype Noteproperty -Value "WINDOWS CLUSTER"
                                            }          




                    # IIS
                    ".*IIS Server Role.*"   
                                            {
                                            $obj | Add-Member -Name "COMPUTER" -membertype Noteproperty -Value $inst.Path
                                            $obj | Add-Member -Name "CLASS" -membertype Noteproperty -Value $classname
                                            $obj | Add-Member -Name "MAIN ROLE" -membertype Noteproperty -Value "IIS"
                                            }          




                    # WINDOWS PRINT SERVER
                    ".*Print Services Role.*"   
                                            {
                                            $obj | Add-Member -Name "COMPUTER" -membertype Noteproperty -Value $inst.Path
                                            $obj | Add-Member -Name "CLASS" -membertype Noteproperty -Value $classname
                                            $obj | Add-Member -Name "MAIN ROLE" -membertype Noteproperty -Value "WINDOWS PRINT SERVER"
                                            }          




                    # WINDOWS DNS
                    ".*Windows DNS Server.*"   
                                            {
                                            $obj | Add-Member -Name "COMPUTER" -membertype Noteproperty -Value $inst.Path
                                            $obj | Add-Member -Name "CLASS" -membertype Noteproperty -Value $classname
                                            $obj | Add-Member -Name "MAIN ROLE" -membertype Noteproperty -Value "WINDOWS DNS"
                                            }          




                    # WSUS
                    ".*(Windows Server Update|WSUS).*"   
                                            {
                                            $obj | Add-Member -Name "COMPUTER" -membertype Noteproperty -Value $inst.Path
                                            $obj | Add-Member -Name "CLASS" -membertype Noteproperty -Value $classname
                                            $obj | Add-Member -Name "MAIN ROLE" -membertype Noteproperty -Value "WSUS"
                                            }          



                    }



                $Finaltableau += $obj

                }

    }


    Else
    {
    $ClassError = "'$classname' class was not found`n"
     
    }



# Clear of $instances variable for each $classname loop
Clear-Variable instances

}



# Display Final Result
$Finaltableau



# Display If some class was not found
If ($ClassError)
{
Write-Host -F Red "SOME CLASSES WAS NOT FOUND:`n$ClassError"
}

 

 

Zabbix – Principe des périodes de maintenance


A l’instar de la plupart des outils de supervision, Zabbix propose un système de mise en maintenance de la supervision.

Pour configurer une nouvelle maintenance, Aller dans le menu Configuration / Maintenance:

image


Cliquer Create Maintenance Period

image


Renseigner le nom de la période.

Intéressant, le choix est donné de collecter ou non les données.

Attention: les champs de date Active Since et Active Till ne représente pas la période de maintenance elle même mais le temps au sein duquel nous allons créer une ou plusieurs périodes dans l’onglet correspondant (Periods)

Dans l’exemple ci-dessous on positionne une plage de temps d’un an.

image


Aller dans l’onglet Periods. Cliquer Add

image


4 modes sont disponibles: One Time Only, Daily, Weekly et Monthly.

imageimageimageimageimage


Dans l’onglet Hosts and groups, selectionner le/les hosts ou le/les host groups

image


Une fois la période crée, elle apparait en état Approaching lorsque la date Active Since approche.

image


Lorsque les hosts concernés sont effectivement en période de maintenance, l’icone image apparait a coté, jusqu’a la fin de la période.


image

image


Dans cet exemple, dans un an, la règle de maintenance passera en mode Expired.

image

Zabbix – Supervision basique d’une URL


Zabbix propose plusieurs manière de superviser des URL. L’exemple ci-dessous propose d’utiliser un ‘Web Scenario’ pour la supervision d’une URL simple (ici www.google.fr).

on commence par créer un template vide qui contiendra la configuration:

image


image


image

NB: Le nom du Host group associé est arbitraire.

Cliquer Add.

image

Le template vide est crée.


image

Cliquer “Create Web Scenario”


image

Name: Check Google

Agent: On positionne Zabbix. ce champs permet de selectionner plusieurs type de client http/navigateur.

Cliquer Steps.


image

Dans la zone Steps, cliquer sur Add.


image

name: Google base page

URL: http://www.google.fr

Required Status codes: 200


image

image

Cliquer Add

image

Le Web scenario est crée.


image

On applique (Link) le template au host devant effectuer le check de supervision.


image


image

Apres quelques minutes les données remonte dans la liste des “Latest data” du host concerné. on voit ici que le code HTTP renvoyé est bien 200 (OK)

On crée a présent un trigger (alerte) en charge declencher une alerte sur le cas ou le code HTTP serait different de 200.

image

image

Dans les propriétés du template, cliquer Triggers


image

cliquer en haut a droite Create Trigger


image

Name: Google Site KO

Clquer sur Add a coté de la zone Expression pour construire la condition de declenchement.


image

Cliquer sur Select pour aller rechercher l’item crée precedemment.


image

Selectionner “Response code for step “Google base page”…”


image

Laisser selectionné la fonction “last()”.

Result: <> 200

cliquer Insert.


image

A titre d’indication ajouter le nom de l’url surveillée dans le champ URL.

Cliquer Add.


image

Le trigger est maintenant actif.

SCOM - Zabbix - Management Pack pour l'agent Zabbix sur Windows

 Dans le cadre de la supervision et/ou du suivi du déploiement de l'agent Zabbix avec Scom, voici un management pack qui:

- Decouvre l'agent zabbix, sa version, ses propriétés "ZabbixPassiveServer" et "ZabbixActiveServer"

- Monitor le service ZabbixAgent

- propose deux console tasks:

       - Restart Zabbix Agent Service

       - Display Agent Configuration File (Chemin du fichier de config overridable)

NB: Les Discovery rules et Monitors sont désactivées par defaut.

 

ZabbixAgent.MP.xml (23,35 kb)

 

<?xml version="1.0" encoding="utf-8"?><ManagementPack ContentReadable="true" SchemaVersion="2.0" OriginalSchemaVersion="1.1" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <Manifest>
    <Identity>
      <ID>ZabbixAgent.MP</ID>
      <Version>1.0.0.3</Version>
    </Identity>
    <Name>ZabbixAgent MP</Name>
    <References>
      <Reference Alias="SCInternal">
        <ID>Microsoft.SystemCenter.Internal</ID>
        <Version>7.0.8433.0</Version>
        <PublicKeyToken>31bf3856ad364e35</PublicKeyToken>
      </Reference>
      <Reference Alias="Windows">
        <ID>Microsoft.Windows.Library</ID>
        <Version>7.5.8501.0</Version>
        <PublicKeyToken>31bf3856ad364e35</PublicKeyToken>
      </Reference>
      <Reference Alias="Performance">
        <ID>System.Performance.Library</ID>
        <Version>7.0.8433.0</Version>
        <PublicKeyToken>31bf3856ad364e35</PublicKeyToken>
      </Reference>
      <Reference Alias="System">
        <ID>System.Library</ID>
        <Version>7.5.8501.0</Version>
        <PublicKeyToken>31bf3856ad364e35</PublicKeyToken>
      </Reference>
      <Reference Alias="SC">
        <ID>Microsoft.SystemCenter.Library</ID>
        <Version>7.0.8433.0</Version>
        <PublicKeyToken>31bf3856ad364e35</PublicKeyToken>
      </Reference>
      <Reference Alias="Health">
        <ID>System.Health.Library</ID>
        <Version>7.0.8433.0</Version>
        <PublicKeyToken>31bf3856ad364e35</PublicKeyToken>
      </Reference>
    </References>
  </Manifest>
  <TypeDefinitions>
    <EntityTypes>
      <ClassTypes>
        <ClassType ID="ZabbixAgent" Accessibility="Public" Abstract="false" Base="Windows!Microsoft.Windows.LocalApplication" Hosted="true" Singleton="false" Extension="false">
          <Property ID="Name" Type="string" AutoIncrement="false" Key="false" CaseSensitive="false" MaxLength="256" MinLength="0" Required="false" Scale="0" />
          <Property ID="Version" Type="string" AutoIncrement="false" Key="false" CaseSensitive="false" MaxLength="256" MinLength="0" Required="false" Scale="0" />
          <Property ID="ZabbixPassiveServer" Type="string" AutoIncrement="false" Key="false" CaseSensitive="false" MaxLength="256" MinLength="0" Required="false" Scale="0" />
          <Property ID="ZabbixActiveServer" Type="string" AutoIncrement="false" Key="false" CaseSensitive="false" MaxLength="256" MinLength="0" Required="false" Scale="0" />


        </ClassType>
        <ClassType ID="ZabbixAgent.MP.Application.Rollup" Accessibility="Public" Abstract="false" Base="System!System.Service" Hosted="false" Singleton="false" Extension="false">
          <Property ID="ApplicationName" Type="string" AutoIncrement="false" Key="true" CaseSensitive="false" MaxLength="256" MinLength="0" Required="false" Scale="0" />
        </ClassType>
      </ClassTypes>
      <RelationshipTypes>
        <RelationshipType ID="ZabbixAgent.MP.Application.Contains.ZabbixAgent" Accessibility="Public" Abstract="false" Base="System!System.Containment">
          <Source ID="Source" MinCardinality="0" MaxCardinality="2147483647" Type="ZabbixAgent.MP.Application.Rollup" />
          <Target ID="Target" MinCardinality="0" MaxCardinality="2147483647" Type="ZabbixAgent" />
        </RelationshipType>
      </RelationshipTypes>
    </EntityTypes>
	<ModuleTypes>
	
		<WriteActionModuleType ID="ZabbixAgent.DisplayAgentConfig.WA" Accessibility="Internal" Batching="false">
        <Configuration>
          <xsd:element minOccurs="1" name="ConfigFilePath" type="xsd:string" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
          <xsd:element minOccurs="1" name="TimeoutSeconds" type="xsd:integer" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
        </Configuration>
        <OverrideableParameters>
          <OverrideableParameter ID="ConfigFilePath" Selector="$Config/ConfigFilePath$" ParameterType="string" />
          <OverrideableParameter ID="TimeoutSeconds" Selector="$Config/TimeoutSeconds$" ParameterType="int" />
        </OverrideableParameters>
        <ModuleImplementation Isolation="Any">
          <Composite>
            <MemberModules>
              <WriteAction ID="PSWA" TypeID="Windows!Microsoft.Windows.PowerShellWriteAction">
                <ScriptName>ZabbixAgent.DisplayAgentConfig.WA.ps1</ScriptName>
                <ScriptBody>
#=================================================================================
#  Script to display Zabbix Agent Configuration File
#=================================================================================

param($ConfigFilePath)

#=================================================================================
# Constants section - modify stuff here:

# Assign script name variable for use in event logging
$ScriptName = "ZabbixAgent.DisplayAgentConfig.Task.ps1"
#=================================================================================


# Gather who the script is running as
$whoami = whoami


# Begin Main Script
#=================================================================================
Write-Host "Task Starting.  Running as $whoami"
#Load agent scripting object
Write-Host "Display Zabbix Agent Config File"
try
	{
	Get-Content -Path $ConfigFilePath
	}
	catch
	{
	write-host "Error during access to $ConfigFilePath file"
	}

#=================================================================================
                </ScriptBody>
                <Parameters>
                  <Parameter>
                    <Name>ConfigFilePath</Name>
                    <Value>$Config/ConfigFilePath$</Value>
                  </Parameter>
                </Parameters>
                <TimeoutSeconds>$Config/TimeoutSeconds$</TimeoutSeconds>
              </WriteAction>
            </MemberModules>
            <Composition>
              <Node ID="PSWA" />
            </Composition>
          </Composite>
        </ModuleImplementation>
        <OutputType>System!System.BaseData</OutputType>
        <InputType>System!System.BaseData</InputType>
      </WriteActionModuleType>
	
	</ModuleTypes>
  </TypeDefinitions>
  <Monitoring>
    <Discoveries>
      <Discovery ID="ZabbixAgent.Discovery" Enabled="false" Target="Windows!Microsoft.Windows.Computer" ConfirmDelivery="false" Remotable="true" Priority="Normal">
        <Category>Discovery</Category>
        <DiscoveryTypes>
          <DiscoveryClass TypeID="ZabbixAgent">
            <Property PropertyID="Name" />
            <Property TypeID="System!System.ConfigItem" PropertyID="ObjectStatus" />
            <Property TypeID="System!System.ConfigItem" PropertyID="AssetStatus" />
            <Property TypeID="System!System.ConfigItem" PropertyID="Notes" />
            <Property TypeID="System!System.Entity" PropertyID="DisplayName" />
          </DiscoveryClass>
        </DiscoveryTypes>
        <DataSource ID="DS" TypeID="Windows!Microsoft.Windows.WmiProviderWithClassSnapshotDataMapper">
          <NameSpace>\\$Target/Property[Type="Windows!Microsoft.Windows.Computer"]/NetworkName$\root\cimv2</NameSpace>
          <Query>SELECT Name, DisplayName, PathName FROM Win32_Service WHERE Name like '%zabbix%'</Query>
          <Frequency>86400</Frequency>
          <ClassId>$MPElement[Name="ZabbixAgent"]$</ClassId>
          <InstanceSettings>
            <Settings>
              <Setting>
                <Name>$MPElement[Name="Windows!Microsoft.Windows.Computer"]/PrincipalName$</Name>
                <Value>$Target/Property[Type="Windows!Microsoft.Windows.Computer"]/PrincipalName$</Value>
              </Setting>
              <Setting>
                <Name>$MPElement[Name="ZabbixAgent"]/Name$</Name>
                <Value>$Data/Property[@Name='Name']$</Value>
              </Setting>
            </Settings>
          </InstanceSettings>
        </DataSource>
      </Discovery>
	     
	  
	 <Discovery ID="ZabbixAgent.Discovery.PowerShell.Properties.Discovery" Enabled="false" Target="ZabbixAgent" ConfirmDelivery="false" Remotable="true" Priority="Normal">
        <Category>Discovery</Category>
        <DiscoveryTypes>
          <DiscoveryClass TypeID="ZabbixAgent">
            <Property PropertyID="Version" />
            <Property PropertyID="ZabbixPassiveServer" />
            <Property PropertyID="ZabbixActiveServer" />
          </DiscoveryClass>
        </DiscoveryTypes>
        <DataSource ID="DS" TypeID="Windows!Microsoft.Windows.TimedPowerShell.DiscoveryProvider">
          <IntervalSeconds>86393</IntervalSeconds>
          <SyncTime />
          <ScriptName>ZabbixAgent.PowerShell.Properties.Discovery.ps1</ScriptName>
          <ScriptBody>
#=================================================================================
#  Script to gather additional properties of zabbix agent via PowerShell
#
#  Author: CJOURDAN
#  v1
#=================================================================================
param($SourceId,$ManagedEntityId,$ComputerName)


# Manual Testing section - put stuff here for manually testing script - typically parameters:
#=================================================================================
# $SourceId = '{00000000-0000-0000-0000-000000000000}'
# $ManagedEntityId = '{00000000-0000-0000-0000-000000000000}'
# $Computername = 'server.domain.com'
# $MGName = ''
# $IP = ''
#=================================================================================


# Constants section - modify stuff here:
#=================================================================================
# Assign script name variable for use in event logging
$ScriptName = "ZabbixAgent.PowerShell.Properties.Discovery.ps1"

#=================================================================================


# Starting Script section - All scripts get this
#=================================================================================
# Gather the start time of the script
$StartTime = Get-Date
#Set variable to be used in logging events
$whoami = whoami
# Load MOMScript API
$momapi = New-Object -comObject MOM.ScriptAPI
#Log script event that we are starting task
$momapi.LogScriptEvent($ScriptName,1006,0,"`nScript is starting.")
#=================================================================================


# Discovery Script section
#=================================================================================
# Load SCOM Discovery module
$DiscoveryData = $momapi.CreateDiscoveryData(0, $SourceId, $ManagedEntityId)
#=================================================================================


# Begin MAIN script section
#=================================================================================


# Get Infos from Zabbix Agent Configuration File
#=======================================================================			
$ZabbixConfFile = "C:\Program Files\zabbix_agents\conf\zabbix_agentd.win.conf"
#=======================================================================

try
{
$FileContent = Get-Content -Path $ZabbixConfFile -ErrorAction Stop
}
catch
{
$momapi.LogScriptEvent($ScriptName,1007,2,"`Error during retrieve of Zabbix Conf File Content")
exit 1
}


$ActiveServer =  $FileContent | Where-Object {$_ -like "ServerActive=*"}

$PassiveServer = $FileContent | Where-Object {$_ -like "Server=*"} 

If (!($ActiveServer) -or $ActiveServer.Length -eq 0)
	{
    #Write-Host "`Error during retrieve of Active Server data"
    $momapi.LogScriptEvent($ScriptName,1007,2,"`Error during retrieve of Active Server data or Active Server is not configured")
	$ActiveServer = "NULL"
	}
    Else
	{
	$ActiveServer = $ActiveServer.Replace('ServerActive=','')
	}


If (!($PassiveServer) -or $PassiveServer.Length -eq 0)
	{
    #write-host "`Error during retrieve of PassiveServer data"
    $momapi.LogScriptEvent($ScriptName,1007,2,"`Error during retrieve of PassiveServer data or Passive Server is not configured")
	$PassiveServer = "NULL"
	}
Else
	{
	$PassiveServer = $PassiveServer.Replace('Server=','')
	}


# Get Infos from Zabbix Agent exe (zabbix_agentd.exe)
#=======================================================================
try
	{
	$Version = $(Get-ChildItem -Path "C:\Program Files\zabbix_agents\bin\win64\zabbix_agentd.exe").VersionInfo.productversion
	}
catch
	{
	#write-host "`Error during retrieve of agent version"
    $momapi.LogScriptEvent($ScriptName,1007,2,"`Error during retrieve of agent version")
	$Version = "NULL"
	}



# Discovery Script section - Discovery scripts get this
#=================================================================================
$instance = $DiscoveryData.CreateClassInstance("$MPElement[Name='ZabbixAgent']$")
$instance.AddProperty("$MPElement[Name='Windows!Microsoft.Windows.Computer']/PrincipalName$", $Computername)
$instance.AddProperty("$MPElement[Name='ZabbixAgent']/Version$", $Version)
$instance.AddProperty("$MPElement[Name='ZabbixAgent']/ZabbixPassiveServer$", $PassiveServer)
$instance.AddProperty("$MPElement[Name='ZabbixAgent']/ZabbixActiveServer$", $ActiveServer)


$DiscoveryData.AddInstance($instance)

# Return Discovery Items Normally           
$DiscoveryData
# Return Discovery Bag to the command line for testing (does not work from ISE)
# $momapi.Return($DiscoveryData)
#=================================================================================


# End of script section
#=================================================================================
#Log an event for script ending and total execution time.
$EndTime = Get-Date
$ScriptTime = ($EndTime - $StartTime).TotalSeconds
$momapi.LogScriptEvent($ScriptName,1008,0,"`nScript has completed.") 
#=================================================================================
# End of script	  
		  </ScriptBody>
          <Parameters>
            <Parameter>
              <Name>SourceId</Name>
              <Value>$MPElement$</Value>
            </Parameter>
            <Parameter>
              <Name>ManagedEntityId</Name>
              <Value>$Target/Id$</Value>
            </Parameter>
            <Parameter>
              <Name>ComputerName</Name>
              <Value>$Target/Host/Property[Type="Windows!Microsoft.Windows.Computer"]/PrincipalName$</Value>
            </Parameter>
            
          </Parameters>
          <TimeoutSeconds>600</TimeoutSeconds>
        </DataSource>
      </Discovery>
    </Discoveries>
   <Tasks>
	<Task ID="ZabbixAgent.RestartZabbixAgent.Task" Accessibility="Public" Enabled="true" Target="ZabbixAgent" Timeout="120" Remotable="true">
        <Category>Custom</Category>
        <WriteAction ID="WA" TypeID="Windows!Microsoft.Windows.ScriptWriteAction">
          <ScriptName>ZabbixAgent.RestartZabbixAgent.Task.vbs</ScriptName>
          <Arguments />
          <ScriptBody>
            Option Explicit
            On Error Resume Next
            Dim ScriptName, oAPI, objWMIService, oShell, oShellEnv, computerName, strCommand, objProcess, objProgram, strShell

            ScriptName = "ZabbixAgent.RestartZabbixAgent.Task.vbs"

            'Load momscript API
            Set oAPI = CreateObject("MOM.ScriptAPI")
            'Log script event that we are starting
            Call oAPI.LogScriptEvent(ScriptName, 1313, 2, "A command to restart the zabbix agent was sent.  We will attempt to stop and then restart the ZabbixAgent now.")

            'Begin Healthservice Restart
            Set oShell = WScript.CreateObject("WScript.Shell")
            set oShellEnv = oShell.Environment("Process")
            computerName = oShellEnv("ComputerName")
            'Echo that we are about to start for task output
            WScript.echo "Beginning Restart attempt for ZabbixAgent on " & computerName
            strCommand = "cmd /c net stop ZabbixAgent & cmd /c net start ZabbixAgent"
            Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
            Set objProcess = objWMIService.Get("Win32_Process")
            Set objProgram = objProcess.Methods_( _
            "Create").InParameters.SpawnInstance_
            objProgram.CommandLine = strCommand
            Set strShell = objWMIService.ExecMethod( _
            "Win32_Process", "Create", objProgram)
            'Echo that we are restarting for task output
            WScript.echo "Restarting ZabbixAgent on " & computerName
            'End ZabbixAgent Restart
          </ScriptBody>
          <TimeoutSeconds>60</TimeoutSeconds>
        </WriteAction>
      </Task>
	  
	  
	  <Task ID="ZabbixAgent.DisplayAgentConfig.Task" Accessibility="Public" Enabled="true" Target="ZabbixAgent" Timeout="120" Remotable="true">
        <Category>Custom</Category>
        <WriteAction ID="PSWA" TypeID="ZabbixAgent.DisplayAgentConfig.WA">
          <ConfigFilePath>C:\Program Files\zabbix_agents\conf\zabbix_agentd.win.conf</ConfigFilePath>
          <TimeoutSeconds>60</TimeoutSeconds>
        </WriteAction>

		
      </Task>
</Tasks>
	<Monitors>
      <UnitMonitor ID="ZabbixAgent.ZabbixAgentService.Monitor" Accessibility="Public" Enabled="false" Target="ZabbixAgent" ParentMonitorID="Health!System.Health.AvailabilityState" Remotable="true" Priority="Normal" TypeID="Windows!Microsoft.Windows.CheckNTServiceStateMonitorType" ConfirmDelivery="false">
        <Category>Custom</Category>
        <OperationalStates>
          <OperationalState ID="ZabbixAgent.ZabbixAgentService.Monitor.OK" MonitorTypeStateID="Running" HealthState="Success" />
          <OperationalState ID="ZabbixAgent.ZabbixAgentService.Monitor.KO" MonitorTypeStateID="NotRunning" HealthState="Error" />
        </OperationalStates>
        <Configuration>
          <ComputerName>$Target/Host/Property[Type="Windows!Microsoft.Windows.Computer"]/NetworkName$</ComputerName>
          <ServiceName>ZabbixAgent</ServiceName>
          <CheckStartupType>true</CheckStartupType>
        </Configuration>
      </UnitMonitor>
    </Monitors>

  

  </Monitoring>
 
  <LanguagePacks>
    <LanguagePack ID="FRA" IsDefault="true">
      <DisplayStrings>
        <DisplayString ElementID="ZabbixAgent.MP">
          <Name>ZabbixAgent MP</Name>
        </DisplayString>
        <DisplayString ElementID="ZabbixAgent.MP.Application.Contains.ZabbixAgent">
          <Name>ZabbixAgent MP Application Contains ZabbixAgent</Name>
          <Description>Defines a System.Containment relationship between ZabbixAgent.MP.Application.Rollup and ZabbixAgent.</Description>
        </DisplayString>
        <DisplayString ElementID="ZabbixAgent.MP.Application.Rollup">
          <Name>ZabbixAgent MP Application Rollup</Name>
        </DisplayString>
        <DisplayString ElementID="ZabbixAgent.MP.Application.Rollup" SubElementID="ApplicationName">
          <Name>Application Name</Name>
          <Description>Application Name</Description>
        </DisplayString>
        <DisplayString ElementID="ZabbixAgent">
          <Name>ZabbixAgent</Name>
        </DisplayString>
        <DisplayString ElementID="ZabbixAgent.Discovery">
          <Name>ZabbixAgent Discovery</Name>
        </DisplayString>
        <DisplayString ElementID="ZabbixAgent.Discovery.PowerShell.Properties.Discovery">
          <Name>ZabbixAgent PowerShell Properties Discovery</Name>
        </DisplayString>

        <DisplayString ElementID="ZabbixAgent" SubElementID="Name">
          <Name>Name</Name>
        </DisplayString>
		<DisplayString ElementID="ZabbixAgent" SubElementID="Version">
          <Name>Version</Name>
        </DisplayString>
		<DisplayString ElementID="ZabbixAgent" SubElementID="ZabbixPassiveServer">
          <Name>ZabbixPassiveServer</Name>
        </DisplayString>
		<DisplayString ElementID="ZabbixAgent" SubElementID="ZabbixActiveServer">
          <Name>ZabbixActiveServer</Name>
        </DisplayString>
		<DisplayString ElementID="ZabbixAgent.ZabbixAgentService.Monitor">
          <Name>Zabbix Agent Service</Name>
        </DisplayString>
        <DisplayString ElementID="ZabbixAgent.ZabbixAgentService.Monitor" SubElementID="ZabbixAgent.ZabbixAgentService.Monitor.OK">
          <Name>Service is running</Name>
        </DisplayString>
        <DisplayString ElementID="ZabbixAgent.ZabbixAgentService.Monitor" SubElementID="ZabbixAgent.ZabbixAgentService.Monitor.KO">
          <Name>Service is not running</Name>
        </DisplayString>
        <DisplayString ElementID="ZabbixAgent.RestartZabbixAgent.Task">
          <Name>Restart Zabbix Agent Service</Name>
        </DisplayString>
        <DisplayString ElementID="ZabbixAgent.DisplayAgentConfig.Task">
          <Name>Display Agent Configuration File</Name>
        </DisplayString>


      </DisplayStrings>

    </LanguagePack>
  
  <LanguagePack ID="ENU" IsDefault="false">
      <DisplayStrings>
        <DisplayString ElementID="ZabbixAgent.MP">
          <Name>ZabbixAgent MP</Name>
        </DisplayString>
        <DisplayString ElementID="ZabbixAgent.MP.Application.Contains.ZabbixAgent">
          <Name>ZabbixAgent MP Application Contains ZabbixAgent</Name>
          <Description>Defines a System.Containment relationship between ZabbixAgent.MP.Application.Rollup and ZabbixAgent.</Description>
        </DisplayString>
        <DisplayString ElementID="ZabbixAgent.MP.Application.Rollup">
          <Name>ZabbixAgent MP Application Rollup</Name>
        </DisplayString>
        <DisplayString ElementID="ZabbixAgent.MP.Application.Rollup" SubElementID="ApplicationName">
          <Name>Application Name</Name>
          <Description>Application Name</Description>
        </DisplayString>
        <DisplayString ElementID="ZabbixAgent">
          <Name>ZabbixAgent</Name>
        </DisplayString>
        <DisplayString ElementID="ZabbixAgent.Discovery">
          <Name>ZabbixAgent Server Discovery</Name>
        </DisplayString>
        <DisplayString ElementID="ZabbixAgent.Discovery.PowerShell.Properties.Discovery">
          <Name>ZabbixAgent PowerShell Properties Discovery</Name>
        </DisplayString>
        <DisplayString ElementID="ZabbixAgent" SubElementID="Name">
          <Name>Name</Name>
        </DisplayString>
		<DisplayString ElementID="ZabbixAgent" SubElementID="Version">
          <Name>Version</Name>
        </DisplayString>
		<DisplayString ElementID="ZabbixAgent" SubElementID="ZabbixPassiveServer">
          <Name>ZabbixPassiveServer</Name>
        </DisplayString>
		<DisplayString ElementID="ZabbixAgent" SubElementID="ZabbixActiveServer">
          <Name>ZabbixActiveServer</Name>
        </DisplayString>
		<DisplayString ElementID="ZabbixAgent.ZabbixAgentService.Monitor">
          <Name>Zabbix Agent Service</Name>
        </DisplayString>
        <DisplayString ElementID="ZabbixAgent.ZabbixAgentService.Monitor" SubElementID="ZabbixAgent.ZabbixAgentService.Monitor.OK">
          <Name>Service is running</Name>
        </DisplayString>
        <DisplayString ElementID="ZabbixAgent.ZabbixAgentService.Monitor" SubElementID="ZabbixAgent.ZabbixAgentService.Monitor.KO">
          <Name>Service is not running</Name>
        </DisplayString>
        <DisplayString ElementID="ZabbixAgent.RestartZabbixAgent.Task">
          <Name>Restart Zabbix Agent Service</Name>
        </DisplayString>
	    <DisplayString ElementID="ZabbixAgent.DisplayAgentConfig.Task">
          <Name>Display Agent Configuration File</Name>
        </DisplayString>


      </DisplayStrings>
    </LanguagePack>
  </LanguagePacks>
</ManagementPack>


 

 

 

 

SCOM - SCRIPT - Fonction powershell pour lister toutes les instances d'une machine

Le script ci-dessous intègre la requête SQL de récupération des instances d'une machine, sous forme de fonction.

All_InstancesForOneAgent_vSQLQuery.ps1

 

# SCRIPT THAT QUERY SCOM DATABASE TO GET ALL INSTANCES OF ALL CLASSES FOR A GIVEN COMPUTER ($TargetAgent)
# $TargetComputer must be Short name of computer because we look for this specific string in name, displayname and path of instances.

param(
#Short name of computer
$TargetComputer = "MyComputer"
)


# Function  Invoke-InstancesFromSQL

Function Invoke-InstancesFromSQL
                            {
                                param(
                                    [string]$dataSource = "MyScomSQLServer\OPSMGR",
                                    [string]$database = "OperationsManager",
                                    [string]$TargetComputer,
                                    [string]$sqlCommand = 
                                            $("Use $Database
                                                SELECT 
                                                   MTV.DisplayName as ClassName
	                                               ,MEGV.Path as Instance_Path
	                                               ,MEGV.Id as Instance_Id
	                                               ,MEGV.[DisplayName] as 'Entity_DisplayName'
	                                               ,MEGV.[Name] as 'Entity_Name'
	                                               ,MEGV.[FullName] as Entity_FullName
                                                   ,[IsManaged]
                                                   ,[IsDeleted]
                                                   ,HealthState = 
													CASE WHEN InMaintenanceMode = '0'
														  THEN 
															CASE [HealthState]
															WHEN '0' THEN 'Not Monitored'
															WHEN '1' THEN 'OK'
															WHEN '2' THEN 'Warning'
															WHEN '3' THEN 'Critical'
															END
														WHEN InMaintenanceMode = '1'
														THEN 
															CASE [HealthState]
															WHEN '0' THEN 'In Maintenance Mode'
															WHEN '1' THEN 'OK'
															WHEN '2' THEN 'Warning'
															WHEN '3' THEN 'Critical'
															END
													END
                                                  ,Is_Available = CASE [IsAvailable]
			                                            WHEN '1' THEN 'YES'
			                                            WHEN '2' THEN 'NO'
			                                            END
                                                  
                                                  ,In_MaintenanceMode = CASE [InMaintenanceMode]
			                                            WHEN '0' THEN 'NO'
			                                            WHEN '1' THEN 'YES'
			                                            END
                                                  
                                                  ,Start_Of_Maintenance = CASE WHEN InMaintenanceMode = '0' 
			                                            THEN null
			                                            ELSE MMV.StartTime
			                                            END
	                                              ,End_Of_Maintenance = CASE WHEN InMaintenanceMode = '0'
			                                            THEN null
			                                            ELSE MMV.ScheduledEndTime
			                                            END
                                                  	                                              
                                                  ,Maintenance_RootCause = 
														CASE WHEN InMaintenanceMode = '0'
														  THEN null
															ELSE 
																CASE MMV.ReasonCode
																WHEN '0' THEN 'Other (Planned)'
																WHEN '1' THEN 'Other (Unplanned)'
																  WHEN '2' THEN 'Hardware: Maintenance (Planned)'
																  WHEN '3' THEN 'Hardware: Maintenance (Unplanned)'
																  WHEN '4' THEN 'Hardware: Installation (Planned)'
																  WHEN '5' THEN 'Hardware: Installation (Unplanned)'
																  WHEN '6' THEN 'Operating System: Reconfiguration (Planned)'
																  WHEN '7' THEN 'Operating System: Reconfiguration (Unplanned)'
																  WHEN '8' THEN 'Application: Maintenance (Planned)'
																  WHEN '9' THEN 'Application: Maintenance (Unplanned)'
																  WHEN '10' THEN 'Application: Installation (Planned)'
																  WHEN '11' THEN 'Application: Unresponsive'
																  WHEN '12' THEN 'Application:  Unstable'
																  WHEN '13' THEN 'Security Issue'
																  WHEN '14' THEN 'Loss of network connectivity (Unplanned)'
																END
															END
                                                  
		                                            ,Maintenance_Reason =   
														CASE WHEN InMaintenanceMode = '0' 
														    THEN null
															    ELSE MMV.Comments
														END
	  
      
                                              FROM [OperationsManager].[dbo].[ManagedEntityGenericView] MEGV

                                              INNER JOIN [dbo].[ManagedTypeView] MTV on MEGV.MonitoringClassId = MTV.Id
                                              INNER JOIN [OperationsManager].[dbo].[MaintenanceModeView] MMV on MEGV.id = MMV.BaseManagedEntityId
                                              WHERE (MEGV.Name  like '%$TargetComputer%' OR MEGV.DisplayName  like '%$TargetComputer%' OR MEGV.Path  like '%$TargetComputer%')
                                              and MTV.LanguageCode = 'ENU'
                                              and MEGV.HealthState is not null
                                              and MEGV.IsDeleted <> '1'
                                              ORDER BY MTV.DisplayName
                                            ")
                                           )


                                    $connectionString = "Data Source=$dataSource; " +
                                    "Integrated Security=SSPI; " +
                                    "Initial Catalog=$database"

                                $connection = new-object system.data.SqlClient.SQLConnection($connectionString)
                                $command = new-object system.data.sqlclient.sqlcommand($sqlCommand,$connection)
                                
                                try
                                {
                                $connection.Open()
                                }
                                catch
                                {
                                write-host -F Red $("Error during sql connection - check the credentials used").ToUpper()
                                exit 1
                                }

                                $adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
                                $dataset = New-Object System.Data.DataSet
                                $adapter.Fill($dataSet) | Out-Null

                                $connection.Close()
                                $dataSet.Tables

                              }


[array]$table = Invoke-InstancesFromSQL -TargetComputer $TargetComputer


write-host "`nCOMPUTER: $TargetComputer"

Write-Host "`nNb Of Objects:"$table.count""

$table | ft -Property ClassName,Instance_Path,Entity_DisplayName,Entity_Name,Entity_FullName,HealthState,Is_Available,In_MaintenanceMode,Start_Of_Maintenance,End_Of_Maintenance,Maintenance_RootCause,Maintenance_Reason



# TO FILTER ON SPECIFIC CLASS
# $table | Where-Object {$_.CLASS_NAME -in ('Windows computer','Health Service Watcher','VMware vSphere Host','VMWare Virtual Machine','HPE ProLiant Server')} | ft -AutoSize



# SIMULATE START OF MAINTENANCE MODE FOR THE INSTANCES
#$table | foreach {Get-SCOMClassInstance -id $_.instance_id} | foreach {start-SCOMMaintenanceMode -instance $_ -WhatIf -EndTime $((Get-Date).AddHours(1))}

 

 

 

 

 

 

Grafana – Ajout de Scom en tant que Data Source et création d’un dashboard des alertes

 

Grafana (https://grafana.com/) est une solution de Dashboard open source particulièrement souple et ouverte grâce a de nombreux plugin et data source intégrables.

Dans cet exemple nous allons ajouter l’accès a une base sql SCOM en tant que Data Source et créer un Dashboard des alertes.

 

clip_image002

Dans la zone Configuration de l’interface Grafana nous selectionnons “Data Sources”

clip_image004

Clic sur “Add data source”

clip_image006

On renseigne un nom

On selectionne le Type “Microsoft SQL Server”

On renseigne le nom de l’instance, la base et le compte d’acces.

Clic sur “Save and Test”

clip_image008

clip_image010

clip_image012

Dans la zone “Create” de Grafana, on selectionne “Dashboard”

On ajoute maintenant au Dashboard, un panel qui sera en fait une brique du dashboard.

clip_image014

On sélectionne le modèle “Table”

clip_image016

On clique sur “Panel Title” en haut du tableau et on sélectionne “Edit”

clip_image018

Dans l’onglet “General”, Dans Title, on renseigne un nom.

clip_image020

On se positionne sur l’onglet “Metrics” et on selectionne dans “Data Source” la source de donnée.

clip_image022

Dans le champ de la première Query (A), on colle le code sql correspondant a une sélection des alertes non closes (fichier sql ci-dessous)

 

 

 

clip_image024

Les données sont immédiatement affichées.

on va maintenant effectuer quelques configuration de formatage.

clip_image026

Dans l’onglet “Options” on augmente le champs “Rows per page” a 1000 pour eviter d’avoir trop de pages.

clip_image028

La colonne Severity nous affiche deux decimale apres la virgule. Inutile dans notre cas car cette valeur correspond a des codes de severité (0,1,2)

clip_image030

Pour cela, dans l’onglet “Column Styles”, on ajoute une règle (+Add)

clip_image032

On selectionne dans “Apply to Columns named” la colonne Severity (au passage, notre règle prend le nom de la colonne sélectionnée)

Et on positionne le champ “Decimals” a 0.

clip_image034

Tres bien, mais il serait plus parlant d’avoir les noms de séverité correspondant a ces codes…

clip_image036

On positionne le champ “Type” a String

clip_image038

Et on fait correspondre a chaque code, la valeur adéquate.

clip_image040

Tres bien. Et pour parfaire ce formatage, on va ajouter un peu de couleur…

clip_image042

Dans le champ Threshold, on va definir que les alertes de séverité 1 prennent une couleur orange (WARNING), et les alertes de séverité 2 une couleur rouge (CRITICAL).

NB: L’ordre des couleurs suit l’ordre des seuils (Threshold), séparés par une virgule.

clip_image044

Et l’on peut appliquer ce formattage de couleur a la celulle, en selectionnant la valeur Cell dans le champ “Color Mode”

clip_image046

clip_image048

clip_image050

N’oublions pas de sauvegarder notre dashboard en haut a droite de l’interface Grafana

clip_image052

clip_image054

Dernier petit réglage pour que notre dashboard se rafraichisse automatiquement

clip_image056

On clique sur les settings du dashboard en haut a droite de l’interface Grafana

clip_image058

clip_image060

On positionne la Time Zone a celle du navigateur (Local browser time) et l’auto-refresh a 1m (1 minute).

On sauvegarde ces réglages via le bouton Save.

SCOM – Script Rapport Etat des instances d’une liste de classe (Sortie Cmdline)

Le script ci-dessous génère un rapport formaté dans la ligne de commande, de l’état des instances d’une liste de classe.

#SCOM - SCRIPT DE REQUETE D'ETAT DES OBJETS D'UNE LISTE DE CLASSE #Variables $MGroup = "MyGroup" $MS= "MyMS" $cred = Get-Credential "MyDomain\" #Liste de classe a recuperer $ClassList = ('SQL DB Engine','SQL Database','SQL DB File','SQL Agent','SQL Reporting Services','SQL Analysis Services') #Import du module SCOM try { Import-Module -Name OperationsManager -ErrorAction stop } catch { write-host -ForegroundColor red "Erreur lors de l'import du module SCOM" } #Connection au management group $MGroup New-SCOMManagementGroupConnection -ComputerName $MS -Credential $cred #Recuperation des classes $MonitoringClasses = $ClassList | foreach {Get-SCOMClass -DisplayName $_} if ($MonitoringClasses -eq $null) { write-host "ERROR - UNABLE TO RETRIEVE CLASSES" -ForegroundColor red } write-host "#################################################### `n" write-host "SCOM Management Group: $MGroup `n" write-host "#################################################### `n`n" #Recuperation des instances de chaque classe foreach ($class in $MonitoringClasses) { $MonitoringObjects = $class | Get-SCOMClassInstance -erroraction silentlycontinue | Sort-Object -Descending -Property HealthState write-host -BackgroundColor white -ForegroundColor blue " **************************************************************** `n" write-host -BackgroundColor white -ForegroundColor blue " *** OBJETS DE LA CLASSE "$class.displayname" `n" write-host -BackgroundColor white -ForegroundColor blue " **************************************************************** `n`n" write-host " --- $(get-date -Format F) --- `n`n" write-host " NUMBER OF OBJECT: $($MonitoringObjects | measure-object | select-object -property count -expandproperty count) `n`n" write-host " STATE ----------------- OBJECT`n`n" foreach ($object in $MonitoringObjects) { switch ($object.HealthState) { "Success" {write-host " " -NoNewline ; write-host -ForegroundColor green $object.HealthState -NoNewline ; write-host " -------- " -NoNewline ; write-host $object.FullName} "Error" {write-host " " -NoNewline ; write-host -ForegroundColor red $object.HealthState -NoNewline ; write-host " -------- " -NoNewline ;write-host $object.FullName} "Warning" {write-host " " -NoNewline ; write-host -ForegroundColor yellow $object.HealthState -NoNewline ; write-host " -------- " -NoNewline ;write-host $object.FullName} "Uninitialized" {write-host " " -NoNewline ; write-host -ForegroundColor blue $object.HealthState -NoNewline ; write-host " -------- " -NoNewline ;write-host $object.FullName} } } "`n" } #Fermeture de la connexion Get-SCOMManagementGroupConnection | Remove-SCOMManagementGroupConnection

SCOM – Script Rapport Etat des instances d’une liste de classe (Sortie Html)

Ci-dessous la version Rapport Html du script de l’état des instances d’une liste de classe.

#SCOM - SCRIPT DE REQUETE D'ETAT DES OBJETS D'UNE LISTE DE CLASSE (AVEC GENERATION RAPPORT HTML) #Variables $MGroup = "MyGroup" $MS= "MyMS" $cred = Get-Credential "MyDomain" #Liste de classe a recuperer $ClassList = ('SQL DB Engine','SQL Database','SQL DB File','SQL Agent','SQL Reporting Services','SQL Analysis Services') $backcolor = "#E0ECF8" #Import du module SCOM try { Import-Module -Name OperationsManager -ErrorAction stop } catch { write-host -ForegroundColor red "Erreur lors de l'import du module SCOM" } #Connection au management group $MGroup New-SCOMManagementGroupConnection -ComputerName $MS -Credential $cred #Recuperation des classes $MonitoringClasses = $ClassList | foreach {Get-SCOMClass -DisplayName $_} if ($MonitoringClasses -eq $null) { write-host "ERROR - UNABLE TO RETRIEVE CLASSES" -ForegroundColor red } $report = "<style>BODY{background-color:$backcolor;}</style>" $report = $report + "<br/>" $report = $report + "############################################################################## <br/>" $report = $report + "SCOM Management Group: <b>$MGroup</b> <br/>" $report = $report + "############################################################################## <br/><br/>" #Recuperation des instances de la classe foreach ($class in $MonitoringClasses) { $MonitoringObjects = $class | Get-SCOMClassInstance -erroraction silentlycontinue | Sort-Object -Descending -Property HealthState $classdisplayname = $class.displayname $report = $report + "&emsp;&emsp;**************************************************************** <br/>" $report = $report + "&emsp;&emsp;*** OBJECTS OF CLASS <b>$classdisplayname</b> <br/>" $report = $report + "&emsp;&emsp;**************************************************************** <br/>" $report = $report + "&emsp;&emsp;--- $(get-date -Format F) --- <br/><br/>" $report = $report + "&emsp;&emsp;NUMBER OF OBJECT: $($MonitoringObjects | measure-object | select-object -property count -expandproperty count) <br/><br/>" $report = $report + "&emsp;&emsp;STATE ---------- OBJECT <br/><br/>" foreach ($object in $MonitoringObjects) { switch ($object.HealthState) { "Success" {$report = $report + $("&emsp;&emsp;"; "<font color=#00DF00>" ; $object.HealthState ; "</font>" ; "--------" ; $object.FullName ; "<br/>")} "Error" {$report = $report + $("&emsp;&emsp;";"<font color=#FF0000>" ; $object.HealthState ; "</font>" ; "--------" ; $object.FullName ; "<br/>")} "Warning" {$report = $report + $("&emsp;&emsp;";"<font color=#FFFF00>" ; $object.HealthState ; "</font>" ; "--------" ; $object.FullName ; "<br/>")} "Uninitialized" {$report = $report + $("&emsp;&emsp;";"<font color=#0000FF>" ; $object.HealthState ; "</font>" ; "--------" ; $object.FullName ; "<br/>")} } } $report = $report + "<br/><br/><br/>" } ConvertTo-Html -Body $report | Set-Content P:\InstanceList.htm #Fermeture de la connexion Get-SCOMManagementGroupConnection | Remove-SCOMManagementGroupConnection #Execution du html Invoke-Expression P:\InstanceList.htm

SCOM – Script Rapport Etat des instances d’une liste de classe (Sortie Cmdline)

Le script ci-dessous génère un rapport formaté dans la ligne de commande, de l’état des instances d’une liste de classe.

 

#SCOM - SCRIPT DE REQUETE D'ETAT DES OBJETS D'UNE LISTE DE CLASSE #Variables $MGroup = "MyGroup" $MS= "MyMS" $cred = Get-Credential "MyDomain\" #Liste de classe a recuperer $ClassList = ('SQL DB Engine','SQL Database','SQL DB File','SQL Agent','SQL Reporting Services','SQL Analysis Services') #Import du module SCOM try { Import-Module -Name OperationsManager -ErrorAction stop } catch { write-host -ForegroundColor red "Erreur lors de l'import du module SCOM" } #Connection au management group $MGroup New-SCOMManagementGroupConnection -ComputerName $MS -Credential $cred #Recuperation des classes $MonitoringClasses = $ClassList | foreach {Get-SCOMClass -DisplayName $_} if ($MonitoringClasses -eq $null) { write-host "ERROR - UNABLE TO RETRIEVE CLASSES" -ForegroundColor red } write-host "#################################################### `n" write-host "SCOM Management Group: $MGroup `n" write-host "#################################################### `n`n" #Recuperation des instances de chaque classe foreach ($class in $MonitoringClasses) { $MonitoringObjects = $class | Get-SCOMClassInstance -erroraction silentlycontinue | Sort-Object -Descending -Property HealthState write-host -BackgroundColor white -ForegroundColor blue " **************************************************************** `n" write-host -BackgroundColor white -ForegroundColor blue " *** OBJETS DE LA CLASSE "$class.displayname" `n" write-host -BackgroundColor white -ForegroundColor blue " **************************************************************** `n`n" write-host " --- $(get-date -Format F) --- `n`n" write-host " NUMBER OF OBJECT: $($MonitoringObjects | measure-object | select-object -property count -expandproperty count) `n`n" write-host " STATE ----------------- OBJECT`n`n" foreach ($object in $MonitoringObjects) { switch ($object.HealthState) { "Success" {write-host " " -NoNewline ; write-host -ForegroundColor green $object.HealthState -NoNewline ; write-host " -------- " -NoNewline ; write-host $object.FullName} "Error" {write-host " " -NoNewline ; write-host -ForegroundColor red $object.HealthState -NoNewline ; write-host " -------- " -NoNewline ;write-host $object.FullName} "Warning" {write-host " " -NoNewline ; write-host -ForegroundColor yellow $object.HealthState -NoNewline ; write-host " -------- " -NoNewline ;write-host $object.FullName} "Uninitialized" {write-host " " -NoNewline ; write-host -ForegroundColor blue $object.HealthState -NoNewline ; write-host " -------- " -NoNewline ;write-host $object.FullName} } } "`n" } #Fermeture de la connexion Get-SCOMManagementGroupConnection | Remove-SCOMManagementGroupConnection