PI Services

Le blog des collaborateurs de PI Services

SCOM – Script Exemple de rapport Cmdline pour un monitor

Le script ci-dessous montre comment facilement sortir de petit rapport en ligne de commande de l’état d’un monitor pour tout les agents.

Dans cet exemple on affiche l’état du rollup monitor de l’espace disque (FreeSpaceMonitorRollup) et l’information de maintenance mode.

 

Function GetLogicDiskFreeSpState 
     
{

     
param(
     
[string]$dataSource = "SQLSERV1\OPSMGR",
     
[string]$database = "OperationsManager",
     
[string]$UnitMonitor = "Microsoft.Windows.Server.%.LogicalDisk.FreeSpaceMonitorRollup",
     
[string]$TypeName = "Microsoft.Windows.Server.%.LogicalDisk",
     
[string]$sqlCommand = 
     
$(
"
                                                             
      /* QUERY THAT GET STATE OF SPECIFIC MONITOR STATE FOR ALL COMPUTERS */
      Use $database
                                                                                    
      DECLARE @UnitMonitor VARCHAR(100)
      DECLARE @TypeName VARCHAR(100)
                                           
                       
      SET @UnitMonitor = '%'+'$UnitMonitor'+'%'
      SET @TypeName = '$TypeName'
                                          
      PRINT 'MONITOR: ' + @UnitMonitor
      PRINT 'CRITERIAS:'
                                           
     ;
     WITH
                                                       
     MAININFO (Monitor,Computer,Disk,HealthState, LastModified,IsAvailable,InMaintenanceMode)
     AS
     (                                           
      SELECT
      MV.Name as Monitor
     ,MEGV.path as Computer
     ,MEGV.Name as Disk
     ,HealthState = CASE WHEN InMaintenanceMode = '0' OR InMaintenanceMode is null  
        THEN     
            CASE MEGV.IsAvailable
                  WHEN '0' THEN 'KO - STATE IS NOT AVAILABLE' -- THIS MEAN THAT THE STATE IS GRAYED IN SCOM CONSOLE DESPITE OF THE OBJECT IS NOT IN MAINTENANCE MODE (AGENT FUNCTIONNAL PROBLEM)
                  WHEN '1' THEN
                    CASE SV.[HealthState]
                        WHEN '0' THEN 'Not Monitored'
                        WHEN '1' THEN 'OK'
                        WHEN '2' THEN 'Warning'
                        WHEN '3' THEN 'Critical'
                    END
                                                   
                END                   
                                                       
            WHEN InMaintenanceMode = '1'
        THEN
            CASE MEGV.IsAvailable
            WHEN '0' THEN 'KO - STATE IS NOT AVAILABLE' -- THIS MEAN THAT THE STATE IS GRAYED IN SCOM CONSOLE DESPITE OF THE OBJECT IS IN MAINTENANCE MODE (AGENT FUNCTIONNAL PROBLEM)
            WHEN '1' THEN
                CASE SV.[HealthState]
                WHEN '0' THEN 'In Maintenance Mode'
                WHEN '1' THEN 'OK'
                WHEN '2' THEN 'Warning'
                WHEN '3' THEN 'Critical'
                END
                                                       
            END                                                                                           
        END

    ,SV.[LastModified] as LastModified
    ,MEGV.IsAvailable
    ,MEGV.InMaintenanceMode
    FROM [OperationsManager].[dbo].[StateView] SV
    INNER JOIN [dbo].[ManagedEntityGenericView] MEGV on SV.BaseManagedEntityId = MEGV.BaseManagedEntityId
    INNER JOIN [dbo].[MonitorView] MV on SV.MonitorId = MV.id
    INNER JOIN [dbo].[ManagedTypeView] MTV on MEGV.MonitoringClassId = MTV.Id
    WHERE MV.Name like @UnitMonitor
    AND MTV.Name like @TypeName
        )
    SELECT
        
    MAININFO.Monitor
   ,MAININFO.Computer
   ,MAININFO.Disk
   ,MAININFO.HealthState
   ,MAININFO.LastModified
   ,MAININFO.IsAvailable
   ,MAININFO.InMaintenanceMode
    FROM MAININFO
            
   ORDER BY computer,Disk
  "
    
)

 
)

 
$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)
 
$command.CommandTimeout=300
 
$connection.Open()

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

 
$connection.Close()

 
#Display Time of Query
"`n"
 
write-host "Query Date: $(get-date -Format F)" -NoNewline
"`n"

#Display Criterias
Write-Host "STATE OF MONITOR `"$UnitMonitor`":"
"`n"
#Display Nb of rows

write-host Nb Of Object: $($dataset.Tables.defaultview.Count)
"`n"

$dataSet.Tables
}



try
{
GetLogicDiskFreeSpState | ft -AutoSize
}
catch
{
write-host -F Red "ERROR DURING EXECUTION OF GetLogicDiskFreeSpState FUNCTION - CHECK THAT YOU ARE LOGGED WITH A RIGHT ACCOUNT OR THAT THE SQL QUERY IS CORRECT"
}

SCOM – Requête SQL des Heartbeat Failure par Primary Management Server

 

La requête ci-dessous permet de lister depuis la base OperationsManager, avec un paramètre J-n, les alertes Heartbeat Failure des agents, par Primary Server, en affichant la durée de l’alerte, son eventuel ticket associé, son status et le status du maintenance mode de l’objet.

 

 

/****** HEARTBEAT FAILURE FOR AGENTS PRIMARY MANAGED BY SPECIFIC MS WITH DURATION, STATUS AND OBJECT MAINTENANCE MODE STATUS ******/

Use OperationsManager

DECLARE @PrimaryServer	VARCHAR(50)
DECLARE @startdate	datetime
DECLARE @Offset	int
DECLARE @enddate	datetime
DECLARE @seconds int
DECLARE @AlertPattern VARCHAR(50)
DECLARE @TicketPattern VARCHAR(50)

SET @PrimaryServer = 'MyPrimaryMS' – Provide a name of Primary if you need to filter on.
SET @enddate = GETDATE()
SET @Offset = 4 – Provide number of days to look back (limited to operational db retention
SET @startdate = DATEADD(day,-@Offset,@enddate)
SET @AlertPattern = 'heartbeat'
SET @TicketPattern = 'Ticket_Number'	-- Provide string pattern that must be found in each ticket


;

WITH 
PrimaryRelation (SourceEntityId,agent,PrimaryServer,TargetEntityId)
AS
(
SELECT R.SourceEntityID,SourceBME.DisplayName as Agent,TargetBME.DisplayName as PrimaryServer, R.TargetEntityID
FROM Relationship R WITH (NOLOCK) 
JOIN BaseManagedEntity SourceBME 
ON R.SourceEntityID = SourceBME.BaseManagedEntityID 
JOIN BaseManagedEntity TargetBME 
ON R.TargetEntityID = TargetBME.BaseManagedEntityID 
WHERE R.RelationshipTypeId = dbo.fn_ManagedTypeId_MicrosoftSystemCenterHealthServiceCommunication() 
AND TargetBME.IsDeleted <> '1'  -- AND THE PRIMARY SERVER IS NOT WAITING TO BE DELETED
AND SourceBME.IsDeleted <> '1' -- AND THE AGENT IS NOT WAITING TO BE DELETED
)


-- Get alert

SELECT
PrimaryServer 
,AlertStringName
,MonitoringObjectDisplayName AS Computer
,(DATEADD(hh,DATEDIFF(hh,getutcdate(),getdate()),av.TimeRaised)) as DownDateTime
,(DATEADD(hh,DATEDIFF(hh,getutcdate(),getdate()),av.TimeResolved)) as RestoredDateTime

,Duration = (
	SELECT CONVERT(varchar, (DateDiff (s, (DATEADD(hh,DATEDIFF(hh,getutcdate(),getdate()),av.TimeRaised)), (DATEADD(hh,DATEDIFF(hh,getutcdate(),getdate()),av.TimeResolved)))) / 86400 ) + ' days ' + 
	CONVERT(varchar, (DateDiff (s, (DATEADD(hh,DATEDIFF(hh,getutcdate(),getdate()),av.TimeRaised)), (DATEADD(hh,DATEDIFF(hh,getutcdate(),getdate()),av.TimeResolved)))) % 86400 / 3600) + ' hours ' +
	CONVERT(varchar, (DateDiff (s, (DATEADD(hh,DATEDIFF(hh,getutcdate(),getdate()),av.TimeRaised)), (DATEADD(hh,DATEDIFF(hh,getutcdate(),getdate()),av.TimeResolved)))) % 86400 % 3600 / 60) + ' min ' +
	CONVERT(varchar, (DateDiff (s, (DATEADD(hh,DATEDIFF(hh,getutcdate(),getdate()),av.TimeRaised)), (DATEADD(hh,DATEDIFF(hh,getutcdate(),getdate()),av.TimeResolved)))) % 86400 % 3600 % 60 % 60) + ' sec ' 
	
	)

,TicketID = CASE
	WHEN TicketID is null THEN 'NO_TICKET'
	WHEN TicketId not like '%'+@TicketPattern+'%' THEN 'NO_TICKET'
	ELSE TicketID
	END
,Alert_ResolutionState = CASE
	WHEN AV.ResolutionState = '255' THEN 'Closed'
	WHEN AV.ResolutionState = '254' THEN 'Resolved'
	WHEN AV.ResolutionState = '251' THEN 'Blackout'
	WHEN AV.ResolutionState = '250' THEN 'Scheduled'
	WHEN AV.ResolutionState = '249' THEN 'Acknowledge'
	WHEN AV.ResolutionState = '248' THEN 'Assigned to Engineering'
	WHEN AV.ResolutionState = '247' THEN 'Awaiting Evidence'
	WHEN AV.ResolutionState = '3' THEN 'Notified'
	WHEN AV.ResolutionState = '0' THEN 'New'
	END
,'Object_was_InMM' = CASE
	WHEN av.MonitoringObjectInMaintenanceMode = '0' THEN 'NO'
	WHEN av.MonitoringObjectInMaintenanceMode = '1' THEN 'YES'
	END
FROM [dbo].[AlertView] av
INNER JOIN [OperationsManager].[dbo].[MTV_HealthService] as MTV_HS on MTV_HS.DisplayName = MonitoringObjectDisplayName
INNER JOIN PrimaryRelation on PrimaryRelation.SourceEntityId = MTV_HS.BaseManagedEntityId
WHERE name like '%'+@AlertPattern+'%'
AND (DATEADD(hh,DATEDIFF(hh,getutcdate(),getdate()),av.TimeRaised)) between DATEADD(day,-@Offset,@enddate) and @enddate
--AND PrimaryServer like '%'+@PrimaryServer+'%' -- Uncomment to see agents managed from specific primary server

SCOM – Requête SQL des agents gérés par une gateway spécifique

La requête SQL ci-dessous affiche les agents gérés par une Gateway spécifique ainsi que le failover configuré ou non.

Use OperationsManager
 
DECLARE @PrimaryServer VARCHAR(50)
SET @PrimaryServer = 'MyGateway'
 
;
 
WITH 
PrimaryRelation (SourceEntityId,agent,PrimaryServer,TargetEntityId)
AS
(
SELECT R.SourceEntityID,SourceBME.DisplayName as Agent,TargetBME.DisplayName as PrimaryServer, R.TargetEntityID
FROM Relationship R WITH (NOLOCK) 
JOIN BaseManagedEntity SourceBME 
ON R.SourceEntityID = SourceBME.BaseManagedEntityID 
JOIN BaseManagedEntity TargetBME 
ON R.TargetEntityID = TargetBME.BaseManagedEntityID 
WHERE R.RelationshipTypeId = dbo.fn_ManagedTypeId_MicrosoftSystemCenterHealthServiceCommunication() 
AND TargetBME.IsDeleted <> '1'  -- AND THE PRIMARY SERVER IS NOT WAITING TO BE DELETED
AND SourceBME.IsDeleted <> '1' -- AND THE AGENT IS NOT WAITING TO BE DELETED
)
,
FailoverRelation (SourceEntityId,agent,FailoverServer,TargetEntityId)
AS
(
SELECT R.SourceEntityID,SourceBME.DisplayName as Agent,TargetBME.DisplayName as FailoverServer, R.TargetEntityID
FROM Relationship R WITH (NOLOCK) 
JOIN BaseManagedEntity SourceBME 
ON R.SourceEntityID = SourceBME.BaseManagedEntityID 
JOIN BaseManagedEntity TargetBME 
ON R.TargetEntityID = TargetBME.BaseManagedEntityID 
WHERE R.RelationshipTypeId = dbo.fn_ManagedTypeId_MicrosoftSystemCenterHealthServiceSecondaryCommunication()
AND TargetBME.IsDeleted <> '1'  -- AND THE FAILOVER SERVER IS NOT WAITING TO BE DELETED
AND SourceBME.IsDeleted <> '1' -- AND THE AGENT IS NOT WAITING TO BE DELETED 
)
 
 
SELECT 
       MTV_HS.[DisplayName] as Agent
       
      ,PrimaryRelation.PrimaryServer
      ,FailoverServer =  -- FIELD RELATED TO 'LEFT OUTER JOIN' ON FailoverRelation TABLE
        CASE
        WHEN FailoverRelation.FailoverServer IS NULL THEN 'NO FAILOVER'
        ELSE FailoverRelation.FailoverServer
        END
      ,[Port]
      ,[InstallTime]
      ,[MaximumQueueSize]
      ,Patch = CASE 
        WHEN [PatchList] like '%UR4%' THEN 'RU4'
        WHEN [PatchList] like '%UR8%' THEN 'RU8'
        WHEN [PatchList] like '%UR11%' THEN 'RU11'
        WHEN [PatchList] = '' THEN '[NO_DATA]'
        END
      ,[IsManuallyInstalled]
      ,[Version]
      ,[ActionAccountIdentity]
      ,[ProxyingEnabled]
      ,[HeartbeatInterval]
      ,[NumberOfMissingHeartBeatsToMarkMachineDown_27AD2E30_EFE0_1A73_8C9D_F0A22B073227] as NumberOfMissingHeartBeatsToMarkMachineDown
      ,MTV_OS.DisplayName as OS
      ,MTV_OS.LogicalProcessors_5CAE4847_F75B_01D0_156E_1658D557B739 as Logic_CPU
      ,MTV_OS.CSDVersion_AFE62B62_74FC_2F06_D8A0_DEE31F14CD33 as ServicePack
      
      
  FROM [OperationsManager].[dbo].[MTV_HealthService] as MTV_HS
  INNER JOIN  [dbo].[MTV_Microsoft$Windows$OperatingSystem] as MTV_OS on MTV_HS.DisplayName = MTV_OS.PrincipalName
 
  INNER JOIN PrimaryRelation on PrimaryRelation.SourceEntityId = MTV_HS.BaseManagedEntityId
  -- THE LEFT OUTER JOIN CAN BE COMMENTED (AND RELATED FIELDS) TO DISPLAY ONLY THE PRIMARY SERVER)
  LEFT OUTER JOIN FailoverRelation on FailoverRelation.SourceEntityId = MTV_HS.BaseManagedEntityId
 
  WHERE IsAgent = '1'
  AND PrimaryServer like '%'+@PrimaryServer+'%'
 
 
  order by MTV_HS.[DisplayName]

SCOM – SQL – Trois requêtes d’inventaires des overrides par type d’objet.

Un peu a la manière du précédent post sur l’inventaire des overrides, les trois requêtes suivantes permettent de lister les overrides selon les types d’objet “Rule”, “Monitor” et “Discovery”.

 

 

/* All Overrides for Rules of language code EUN and FRA, with Original MP and Rule, Parameter Name, Override Value, Scope and Containing MP */ Use OperationsManager SELECT mpv2.DisplayName as Rule_MP_Name ,rv.DisplayName as Rule_Name ,IsEnabledByDefault = CASE WHEN rv.Enabled = '0' THEN 'NO' WHEN rv.Enabled <> '0' THEN 'YES' END ,op.OverrideableParameterName as Overrideable_Parameter ,mo.Value as Override_Value ,IsEnforced = CASE WHEN mo.Enforced = '0' THEN 'NO' WHEN mo.Enforced = '1' THEN 'YES' END ,mt.TypeName as Override_Scope ,bme.DisplayName as Override_InstanceName ,bme.Path as Override_InstancePath ,mpv.DisplayName as Override_MP_Name FROM ModuleOverride mo INNER JOIN managementpackview mpv on mpv.Id = mo.ManagementPackId INNER JOIN ruleview rv on rv.Id = mo.ParentId INNER JOIN ManagedType mt on mt.managedtypeid = mo.TypeContext INNER JOIN [dbo].[OverrideableParameter] op on op.OverrideableParameterId = mo.OverrideableParameterId INNER JOIN managementpackview mpv2 on mpv2.Id = rv.ManagementPackId LEFT JOIN BaseManagedEntity bme on bme.BaseManagedEntityId = mo.InstanceContext WHERE mpv.Sealed = 0 AND rv.LanguageCode in ('ENU','FRA') AND mpv.LanguageCode in ('ENU','FRA') AND mpv2.LanguageCode in ('ENU','FRA') --ORDER BY mpv2.DisplayName

 

/*All Overrides for Monitor of language code EUN and FRA, with Original MP and Monitor, Parameter Name, Override Value, Scope and Containing MP */ Use OperationsManager SELECT mpv2.DisplayName as Monitor_MP_Name ,mv.DisplayName as Monitor_Name ,IsEnabledByDefault = CASE WHEN mv.Enabled = '0' THEN 'NO' WHEN mv.Enabled <> '0' THEN 'YES' END ,op.OverrideableParameterName as Overrideable_Parameter ,mo.Value as Override_Value ,IsEnforced = CASE WHEN mo.Enforced = '0' THEN 'NO' WHEN mo.Enforced = '1' THEN 'YES' END ,mt.TypeName as Override_Scope ,bme.DisplayName as Override_InstanceName ,bme.Path as Override_InstancePath ,mpv.DisplayName as Override_MP_Name FROM MonitorOverride mo INNER JOIN managementpackview mpv on mpv.Id = mo.ManagementPackId INNER JOIN monitorview mv on mv.Id = mo.MonitorId INNER JOIN ManagedType mt on mt.managedtypeid = mo.TypeContext INNER JOIN [dbo].[OverrideableParameter] op on op.OverrideableParameterId = mo.OverrideableParameterId INNER JOIN managementpackview mpv2 on mpv2.Id = mv.ManagementPackId LEFT JOIN BaseManagedEntity bme on bme.BaseManagedEntityId = mo.InstanceContext WHERE mpv.Sealed = 0 AND mv.LanguageCode in ('ENU','FRA') AND mpv.LanguageCode in ('ENU','FRA') AND mpv2.LanguageCode in ('ENU','FRA') ORDER BY mpv2.DisplayName

 

-- All Overrides for Discoveries of language code EUN and FRA, with Original MP and Discovery, Parameter Name, Override Value, Scope and Containing MP */ Use OperationsManager SELECT mpv2.DisplayName as Discovery_MP_Name ,dv.DisplayName as Discovery_Name ,mo.ParentType ,IsEnabledByDefault = CASE WHEN dv.Enabled = '0' THEN 'NO' WHEN dv.Enabled <> '0' THEN 'YES' END ,op.OverrideableParameterName as Overrideable_Parameter ,mo.Value as Override_Value ,IsEnforced = CASE WHEN mo.Enforced = '0' THEN 'NO' WHEN mo.Enforced = '1' THEN 'YES' END ,mt.TypeName as Override_Scope ,bme.DisplayName as Override_InstanceName ,bme.Path as Override_InstancePath ,mpv.DisplayName as Override_MP_Name FROM ModuleOverride mo INNER JOIN managementpackview mpv on mpv.Id = mo.ManagementPackId INNER JOIN DiscoveryView dv on dv.Id = mo.ParentId INNER JOIN ManagedType mt on mt.managedtypeid = mo.TypeContext INNER JOIN [dbo].[OverrideableParameter] op on op.OverrideableParameterId = mo.OverrideableParameterId INNER JOIN managementpackview mpv2 on mpv2.Id = dv.ManagementPackId LEFT JOIN BaseManagedEntity bme on bme.BaseManagedEntityId = mo.InstanceContext WHERE mpv.Sealed = 0 AND dv.LanguageCode in ('ENU','FRA') AND mpv.LanguageCode in ('ENU','FRA') AND mpv2.LanguageCode in ('ENU','FRA') AND mo.ParentType = 'Discovery' ORDER BY mpv2.DisplayName

SCOM - Requête SQL pour afficher toutes les règles ayant au moins un override ou aucun

 

 

-- QUERY TO DISPLAY ALL RULES WITH TARGET CLASSES AND THEIR OVERRIDE STATE (ANYWAY MORE THAN 1 OVERRIDE PER RULE) - (FILTERED ON 'ENU' AND 'FRA' LANGUAGES) -- THE FINAL 'GROUP BY' CLAUSE IS TO DISPLAY ONLY ONE RULE OCCURENCE (WE ONLY WANT TO KNOW THAT RULE IS OVERRIDEN AT LEAST ONE TIME. -- THAT IS EQUIVALENT TO DELETE THE 'ALL' STATEMENT IN UNION CLAUSE. PRINT 'ALL RULES THAT IS OVERRIDEN AT LEAST 1 TIME OR NOT'; WITH TEMP1 (Rule_Name,Target_Class,Override_State) AS ( SELECT rv.DisplayName as Rule_Name ,MTV.DisplayName as Target_Class ,Override_State = CASE WHEN mo.ParentId is null THEN 'NOT OVERRIDEN' WHEN mo.ParentId is not null THEN 'OVERRIDEN' END FROM RuleView rv FULL JOIN ModuleOverride mo on rv.Id = mo.ParentId INNER JOIN [dbo].[ManagedTypeView] MTV on rv.TargetMonitoringClassId = MTV.Id WHERE rv.Id not in (select mo.ParentId from ModuleOverride mo) AND rv.LanguageCode in ('ENU','FRA') AND MTV.LanguageCode in ('ENU','FRA') UNION ALL SELECT rv.DisplayName as Rule_name ,MTV.DisplayName as Target_Class ,Override_State = CASE WHEN mo.ParentId is null THEN 'NOT OVERRIDEN' WHEN mo.ParentId is not null THEN 'OVERRIDEN' END FROM RuleView rv FULL JOIN ModuleOverride mo on rv.Id = mo.ParentId JOIN [dbo].[ManagedTypeView] MTV on rv.TargetMonitoringClassId = MTV.Id WHERE rv.Id in (select mo.ParentId from ModuleOverride mo) AND rv.LanguageCode in ('ENU','FRA') AND MTV.LanguageCode in ('ENU','FRA') ) SELECT Rule_Name ,Target_Class ,Override_State FROM TEMP1 GROUP BY Rule_Name,Target_Class,Override_State ORDER BY Rule_Name

SCOM – Script Mode Maintenance des Health Service Watcher

Lors du basculement d’agents gérés par une gateway vers une gateway de secours (failover), il peut arriver que quelques alertes “Heartbeat Failure” indésirables soit générées.

Le script suivant propose de lister, démarrer  ou arrêter les modes maintenance des instances Health Service Watcher des agents gérés par une gateway/management server donné.

Cette action est bien entendu possible pour une autre classe, dans la mesure ou le DisplayName  de l’instance correspond a celui de l’agent.

 

 

########################################################################################################################################### ## SCRIPT TO START/STOP/DISPLAY MAINTENANCE MODE FOR HEALTH SERVICE WATCHER OBJECTS THAT DEPENDS FROM SPECIFIC MANAGEMENT SERVER OR GATEWAY ## Author: CJOURDAN ########################################################################################################################################### #Parameters # $MGroup : Management Group to connect to # $MStoConnect : Management server to connect to # $PrimMS : Management server or Gateway FQDN from which depend agents. # $Reason : Reason for Maintenance Mode (Valid Reason are: PlannedOther # UnPlannedOther # PlannedHardwareMaintenance # UnplannedHardwareMaintenance # PlannedHardwareInstallation # UnplannedHardwareInstallation # PlannedOperatingSystemReconfiguration # UnplannedOperatingSystemReconfiguration # PlannedApplicationMaintenance # ApplicationInstallation # ApplicationUnresponsive # ApplicationUnstable # SecurityIssue # LossOfNetworkConnectivity) # # $Comment : Comment for Maintenance Mode # $MMAction : START or STOP OR DISPLAY Maintenance Mode # $MMDuration : Maintenance Mode Duration in minutes (only valuable for START $MMAction) # EXAMPLES: # Display Health Service Watcher Maintenance Mode Status for agents primary managed by MyPriMaryMS.mydomain.home # .\ScomSwitchMM.ps1 -MGroup MyMGROUP -MStoConnect MyMS.mydomain.home -PrimMS MyPriMaryMS.mydomain.home -MMAction display # Start Health Service Watcher Maintenance Mode for agents primary managed by MyPriMaryMS.mydomain.home during 60 min # .\ScomSwitchMM.ps1 -MGroup MyMGROUP -MStoConnect MyMS.mydomain.home -PrimMS MyPriMaryMS.mydomain.home -MMAction start -MMDuration 60 Param( [Parameter(Mandatory=$false)] $ClassName = "Health Service Watcher", [Parameter(Mandatory=$false)] $MGroup = "MyMGROUP", [Parameter(Mandatory=$false)] $MStoConnect= "MyMS.mydomain.home", [Parameter(Mandatory=$true)] $PrimMS= "MyPriMaryMS.mydomain.home", [Parameter(Mandatory=$false)] $Reason = "PlannedOther", [Parameter(Mandatory=$false)] $Comment = "", [Parameter(Mandatory=$true)] $MMAction = $(Read-Host -Prompt "PROVIDE TYPE OF MAINTENANCE MODE ACTION: START or STOP OR DISPLAY"), [Parameter(Mandatory=$false)] # $MMDuration in minutes $MMDuration = 0 ) if ($MMAction -notmatch ".*STOP.*|.*START.*|.*DISPLAY.*") { write-host -ForegroundColor Yellow "YOU MUST PROVIDE VALID MAINTENANCE MODE ACTION TYPE: START or STOP or DISPLAY" EXIT 1 } $cred = $(Get-Credential -Credential "MyDomain\") #Import du module SCOM try { Import-Module -Name OperationsManager -ErrorAction stop } catch { write-host -ForegroundColor red "Error during import of SCOM PS Module" EXIT 1 } #Connection au management group $MGroup try { New-SCOMManagementGroupConnection -ComputerName $MStoConnect -Credential $cred } catch { write-host -ForegroundColor red "Error during connection to MS $MStoConnect - CHECK CREDENTIALS USED" EXIT 1 } # Get Scom agents that have $PrimMS as Primary Management Server $agents = get-scomagent | where {$_.PrimaryManagementServerName -eq $PrimMS} if (!($agents)) { write-host "NO SCOM AGENTS FOUND FOR SERVER $PrimMS - CHECK THAT THE NAME IS CORRECT (YOU MUST PROVIDE FQDN) OR THAT THIS SERVER BELONG TO $MGroup MANAGEMENT GROUP" EXIT 1 } # Get "Health Service Watcher" Class Instances $class = Get-SCOMClass -DisplayName $ClassName switch($MMAction) { START { # Get instances of "Health Service Watcher" Class $ClassInstances = Get-SCOMClassInstance -Class $class # Class to put in MM Table $ClassInstToMM = @() # Get class instances that match agents foreach ($agent in $agents) { $ClassInstToMM += ($ClassInstances | Where-Object {$_.DisplayName -eq $agent.displayname}) } $starttime = $(get-date).ToUniversalTime() $endtime = $(get-date).AddMinutes($MMDuration).ToUniversalTime() # PUT IN Maintenance Mode $($ClassInstToMM | foreach {$_.schedulemaintenancemode($starttime,$endtime,$Reason,$Comment)}) # Display effective instances in MM write-host "EFFECTIVE INSTANCES OF CLASS '$ClassName' IN MAINTENANCE MODE (Primary Managed by $PrimMS):" # Get instances of "Health Service Watcher" Class $ClassInstances = Get-SCOMClassInstance -Class $class $ClassInstInMM = @() # Get class instances that match agents foreach ($agent in $agents) { $ClassInstInMM += ($ClassInstances | Where-Object {$_.DisplayName -eq $agent.displayname}) } $ClassInstInMM } STOP { # Get instances of "Health Service Watcher" Class $ClassInstances = Get-SCOMClassInstance -Class $class # Class to put out of MM Table $ClassInstOoMM = @() # Get class instances that match agents foreach ($agent in $agents) { $ClassInstOoMM += ($ClassInstances | Where-Object {$_.DisplayName -eq $agent.displayname}) } # Only Endttime in necessary and it is now $endtime = $(get-date).ToUniversalTime() # PUT IN Maintenance Mode $($ClassInstOoMM | foreach {$_.stopmaintenancemode($endtime)}) # Display effective instances in MM write-host "EFFECTIVE INSTANCES OF CLASS '$ClassName' OUT OF MAINTENANCE MODE (Primary Managed by $PrimMS):" # Get instances of "Health Service Watcher" Class $ClassInstances = Get-SCOMClassInstance -Class $class $ClassInstOoMM = @() # Get class instances that match agents foreach ($agent in $agents) { $ClassInstOoMM += ($ClassInstances | Where-Object {$_.DisplayName -eq $agent.displayname}) } $ClassInstOoMM } DISPLAY { # Display effective instances in MM write-host "`n INSTANCES OF CLASS '$ClassName' MAINTENANCE MODE STATE (Primary Managed by $PrimMS):" # Get instances of "Health Service Watcher" Class $ClassInstances = Get-SCOMClassInstance -Class $class $ClassInstMM = @() # Get class instances that match agents foreach ($agent in $agents) { $ClassInstMM += ($ClassInstances | Where-Object {$_.DisplayName -eq $agent.displayname}) } $ClassInstMM } }

SCOM – SQL – Requête d’inventaire des overrides

La requête ci-dessous permet de lister tout les overrides de manière ‘clarifiés’ afin d’identifier les objets a la source de ces overrides, les paramètres concernés et les management pack sources et de destination.

Les paramètres @Startdate et @EndDate permettent de spécifier une fenêtre de temps concernant les dates de création et de dernière modification des overrides.

 

 

declare @StartDate  datetime declare @EndDate    datetime set @EndDate = GETDATE() set @StartDate = DATEADD(day,-60,@EndDate)   SELECT DISTINCT MP.MPFriendlyName AS 'Management Pack' , aov.ParentType AS 'Type' ,(CASE        WHEN AOV.OverrideType = 'RuleProperty' THEN R.RuleName        WHEN AOV.OverrideType = 'MonitorProperty' THEN M.MonitorName        WHEN AOV.OverrideType = 'RuleConfiguration' THEN R.RuleName        WHEN AOV.OverrideType = 'MonitorConfiguration' THEN M.MonitorName  END) AS 'NameType', mt.DisplayName AS ContextDisplayName , aov.OverrideableParameterName , aov.Value, (CASE Enforced        WHEN '0' THEN 'False'        WHEN '1' THEN 'True'   END) AS 'Enforced'   , aov.LastModified   , aov.TimeAdded   ,(CASE   WHEN AOV.OverrideType = 'RuleProperty' THEN              (CASE R.RuleEnabled              WHEN '0' THEN 'False'              WHEN '2' THEN 'True'              WHEN '3' THEN 'True'              WHEN '4' THEN 'True'              END)     WHEN AOV.OverrideType = 'MonitorProperty' THEN              (CASE M.MonitorEnabled              WHEN '0' THEN 'False'              WHEN '2' THEN 'True'              WHEN '3' THEN 'True'              WHEN '4' THEN 'True'              END)     WHEN AOV.OverrideType = 'RuleConfiguration' THEN              (CASE R.RuleEnabled              WHEN '0' THEN 'False'              WHEN '2' THEN 'True'              WHEN '3' THEN 'True'              WHEN '4' THEN 'True'              END)                WHEN AOV.OverrideType = 'MonitorConfiguration' THEN              (CASE M.MonitorEnabled              WHEN '0' THEN 'False'              WHEN '2' THEN 'True'              WHEN '3' THEN 'True'              WHEN '4' THEN 'True'              END) END) AS 'Enable_by_default', MPSTORE.MPFriendlyName AS 'MP Stored'   FROM AllOverrideView AS aov LEFT OUTER JOIN Rules AS R WITH (nolock) ON aov.TargetId = R.RuleId AND (aov.OverrideType = 'RuleProperty' OR aov.OverrideType = 'RuleConfiguration') LEFT OUTER JOIN Monitor AS M WITH (nolock) ON aov.TargetId = M.MonitorId AND (aov.OverrideType = 'MonitorProperty' OR aov.OverrideType = 'MonitorConfiguration') LEFT OUTER JOIN  ManagementPack AS MP WITH (nolock) ON (CASE                                                                                               WHEN AOV.OverrideType = 'RuleProperty' THEN R.ManagementPackId                                                                                               WHEN AOV.OverrideType = 'RuleConfiguration' THEN R.ManagementPackId                                                                                               WHEN AOV.OverrideType = 'MonitorProperty' THEN M.ManagementPackId                                                                                               WHEN AOV.OverrideType = 'MonitorConfiguration' THEN M.ManagementPackId                                                                                               END) = MP.ManagementPackId INNER JOIN ManagementPack AS MPSTORE WITH (nolock) ON MPSTORE.ManagementPackId = aov.ManagementPackId LEFT OUTER JOIN ManagedTypeView AS mt WITH (nolock) ON mt.Id = aov.ContextId LEFT OUTER JOIN ManagedTypeView AS mtv WITH (nolock) ON mtv.Id = aov.ContextObjectId   WHERE (MP.MPFriendlyName IS NOT NULL) AND (aov.LastModified BETWEEN @StartDate AND @EndDate) OR (MP.MPFriendlyName IS NOT NULL) AND (aov.TimeAdded BETWEEN @StartDate AND @EndDate)   ORDER BY aov.TimeAdded DESC

Utilisation de WinSCP .Net Assembly et COM library

Dans cet article nous allons apprendre l'utilisation et l'importance de WinSCP .Net Assembly et COM library.

Introduction

Nous sommes habitué à utiliser le client WinSCP pour se connecter sur un serveur SFTP,SCP ou FTP. Il existe même un module très basique appelé WinSCP.com pour envoyer ou réceptionner des données via un fichier *.bat. Cependant, beaucoup d'entre nous ignore l'existance de WinSCP .Net Assembly et COM library qui offre la possibilité de manipuler des fichiers à distance depuis un environnement supportant .NET, par exemple C#,VB. Net, PowerShell,SSIS et même depuis les sites MS AZURE.

WinSCP .Net assembly et COM library offrent beaucoup de possibilité en termes de ligne de commandes pour automatiser l'envoi et la réception de fichier depuis un serveur FTP,SCP ou sFTP. 

Prérequis

Télécharger le fichier zip indiqué ci-dessous et décompresser le.

Exemple de programmation en PoSH

  • L'initialisation d'une connexion sur un serveur
try
{
    # appel WinSCP .NET assembly
    Add-Type -Path "WinSCPnet.dll"
 
    # paramètre de connexion
    $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
        Protocol = [WinSCP.Protocol]::Sftp
        HostName = "example.com"
        UserName = "user"
        Password = "mypassword"
        SshHostKeyFingerprint = "ssh-rsa 2048 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"
    }
 
    $session = New-Object WinSCP.Session
 
    try
    {
        # initialiser la connexion
        $session.Open($sessionOptions)
 
        Write-Host "You are now connected!!!"
    }
    finally
    {
        # Déconnecter et nettoyer
        $session.Dispose()
    }
 
    exit 0
}
catch [Exception]
{
    # Exception
    Write-Host ("Error: {0}" -f $_.Exception.Message)
    exit 1
}

Pour se connecter sur un serveur sFTP avec une clé privée et sans login et mot de passe, remplacer la ligne :

Password = "mypassword"
        SshHostKeyFingerprint = "ssh-rsa 2048 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"

par 

SshPrivateKeyPath = "chemin vers la clé privée"
        GiveUpSecurityAndAcceptAnySshHostKey = "true"
  • Télécharger un fichier 

Pour télécharger un fichier avec son nom, utiliser la ligne de commande ci-dessous:

$session.GetFiles($session.EscapeFileMask(<chemin complet du fichier>), <destination locale>).Check()
  • Pour uploader un fichier 
 # Upload files
        $transferOptions = New-Object WinSCP.TransferOptions
        $transferOptions.TransferMode = [WinSCP.TransferMode]::Binary
 
        $transferResult = $session.PutFiles("d:\toupload\*", "/home/user/", $False, $transferOptions)

 

Pour avoir plus d'informations sur les classes existantes : https://winscp.net/eng/docs/library

 

Quest RUM : Script de désinstallation des agents

Bonjour à tous !

Lors d'une migration effectuée à l'aide du produit Quest Migration Manager for Active Directory, vous vous retrouvez souvent en fin de migration avec un nombre conséquent d'agents Quest à désinstaller de tous les postes migrés.

Ce que vous pouvez très bien faire à l'aide de Quest RUM (Resource Updating Manager) via l'option Cleanup :

Mais il peut arriver qu'entre temps que certains postes migrés soient devenus indisponibles. Plutôt que de refaire une passe numéro X pour désinstaller les agents, nous allons voir comment automatiser la désinstallation de ceux-ci.

Prérequis

Pour ce faire, il vous faut :

  • Un serveur sur lequel sera placé un partage accessible par toutes les machines ayant un agent Quest
  • Un éditeur de script Powershell
  • Une console d'édition de stratégies de groupe

Le partage de fichiers

Afin que notre script de désinstallation puisse écrire les logs nécessaire, il doit avoir à disposition un partage sur lequel les machines concernées puissent avoir un droit d'écriture de fichiers.

Par défaut, le script va utiliser le nom de partage QuestUninstallLogs$ mais vous pourrez le modifier via les arguments du script. Nous rajoutons un à la fin du nom du partage afin de masquer celui-ci.

Il faut ajouter sur le partage (droit de partage) le droit en modification pour le groupe Everyone.

Il faut ajouter sur le dossier (droit NTFS) le droit en modification et en écriture pour le groupe Authenticated Users

Une fois cela fait, nous pouvons passer à l'édition du script.

Le script

Arguments

Le script s'appelle à l'aide des arguments suivants :

  • -Pole (obligatoire) : Nom du dossier de 1er niveau des logs
  • -Site (obligatoire) : Nom du dossier de 2ème niveau des logs
  • -LogServer (obligatoire) : Nom du serveur devant recevoir les logs
  • -LogShare (facultatif) : Nom du partage devant recevoir les logs

Sortie

Deux types de fichiers de logs vont être générés en sortie dans le chemin indiqué en paramètre du script :

  • XXX_SUMMARY.log : Fichier résumant toutes les désinstallations effectuées par le script
  • COMPUTERS\PC-XXX.log : Fichier détaillant le déroulement de la désinstallation de l'agent Quest pour le poste concerné

Code

#-------------------#
# Script Parameters #
#-------------------#
# Description
# The Uninstall_Quest_Agent script is uninstalling the Quest RUM Agent
# 
# How to use it 
#
# .\Uninstall_Quest_Agent.ps1 -Pole "POLE_IDF" -Site "Site_1" -LogServer "LOG_SERVER_1" -LogShare "QuestUninstallLogs$"
#
# -Pole = Targeted Pole
# -Site = Targeted Site
# -LogServer = Server on which the uninstall logs will be stored
# -LogShare (not mandatory) = Network Share on which the uninstall logs will be stored

########## PARAMETERS ##########

[CmdletBinding(DefaultParametersetName="Common")]
param(
	
	#Attribute field to check
	[Parameter(Mandatory=$true,Position=1)][string] $Pole = $null,
	
	#Attribute field to check
	[Parameter(Mandatory=$true,Position=2)][string] $Site = $null,
	
	#Attributes fields to check
	[Parameter(Mandatory=$false,Position=3)][string] $LogServer = $null,

	#Attributes fields to check
	[Parameter(Mandatory=$false,Position=4)][string] $LogShare = "QuestUninstallLogs$"
	
	)

########## SCRIPT EXECUTION ##########

# Check if script has been executed (log file already exists)

# Define logfile path and name
# Detailed logs
$LogFileDirectoryPath = "\\" + $LogServer + "\" + $LogShare + "\" + $Pole + "\" + $Site + "\COMPUTERS"
$LogFileName = $env:computername + ".log"
$LogFilePath = $LogFileDirectoryPath + "\" + $LogFileName

# Summary logs
$SummaryLogFileDirectoryPath = "\\" + $LogServer + "\" + $LogShare + "\" + $Pole + "\" + $Site
$SummaryLogFileName = $Pole + "_" + $Site + "_" + "SUMMARY.log"
$SummaryLogFilePath = $SummaryLogFileDirectoryPath + "\" + $SummaryLogFileName

# End script if Quest Agent Service is missing
$Service = Get-Service QsRUMAgent -ErrorAction SilentlyContinue

if($Service -eq $null)
{
    Exit
}

########## LOG FILES MANAGMENT ##########

# Checking if directories need to be created

# Check if pole directory exists
$PoleFilePath = "\\" + $LogServer + "\" + $LogShare + "\" + $Pole

# If directory don't exist, we create it
if(!(Test-Path $PoleFilePath))
{
    New-Item $PoleFilePath -ItemType Directory
}

# Check if site directory exists
$SiteFilePath = "\\" + $LogServer + "\" + $LogShare + "\" + $Pole + "\" + $Site

# If directory don't exist, we create it
if(!(Test-Path $SiteFilePath))
{
    New-Item $SiteFilePath -ItemType Directory
}

# Check if COMPUTERS directory exists
$ComputersFilePath = "\\" + $LogServer + "\" + $LogShare + "\" + $Pole + "\" + $Site + "\COMPUTERS"

# If directory don't exist, we create it
if(!(Test-Path $ComputersFilePath))
{
    New-Item $ComputersFilePath -ItemType Directory
}

########## UNINSTALLING AGENT ##########

$Date = (Get-Date).ToString()
$ComputerName = "\\" + $env:computername

# Log
$ToWrite = $Date + " - " + "Begining of Quest agent uninstallation"
Add-Content $LogFilePath $ToWrite

# Stopping and Deleting Quest Migration Manager RUM Agent Service
$Service = Get-Service QsRUMAgent -ErrorAction SilentlyContinue

#If service exists
if($Service)
{
    Stop-Service $Service.Name
    # Log
    $ToWrite = $Date + " - " + "Quest Migration Manager RUM Agent Service - Stopped"
    Add-Content $LogFilePath $ToWrite

    sc.exe $ComputerName delete $Service.Name
    # Log
    $ToWrite = $Date + " - " + "Quest Migration Manager RUM Agent Service - Deleted"
    Add-Content $LogFilePath $ToWrite

    # Log Général
    $ToWrite = $Date + " - " + $env:computername + " - " + "Agent Deleted"
    Add-Content $SummaryLogFilePath $ToWrite
}

else
{
    # Log
    $ToWrite = $Date + " - " + "ERROR : Quest Migration Manager RUM Agent Service not found !"
    Add-Content $LogFilePath $ToWrite
}

# Deleting Quest Migration Manager RUM Agent Directory
$QuestAgentDirectory = "$env:SystemRoot\Quest Resource Updating Agent"

#If directory exists
if(Test-Path $QuestAgentDirectory)
{
    Remove-Item $QuestAgentDirectory -Recurse
    # Log
    $ToWrite = $Date + " - " + "Quest Migration Manager RUM Agent Directory - Deleted"
    Add-Content $LogFilePath $ToWrite
}

else
{
    # Log
    $ToWrite = $Date + " - " + "ERROR : Quest Migration Manager RUM Agent Directory not found !"
    Add-Content $LogFilePath $ToWrite
}

# Log
$ToWrite = $Date + " - " + "End of Quest agent uninstallation"
Add-Content $LogFilePath $ToWrite

Utilisation du script

Vous pouvez utiliser ce script directement sur le poste concerné ou par GPO pour une désinstallation groupée.

Par GPO, le script s'utilise dans la section Powershell dans les Paramètres Ordinateurs de la console de configuration des GPO.

Le chemin pour y accéder est Configuration Ordinateur > Stratégies > Paramètres Windows > Arrêt > Scripts Powershell

A minima, le script doit s'appeller à l'aide des paramètres suivants :

Au fur et à mesure que le script est exécuté, vous devriez voir le dossier des logs se remplir, que ce soit pour le log SUMMARY qui résume toutes les désinstallations ou pour les logs individuels par machine.

HPOneView – Script Powershell

Le script ci-dessous utilise le module powershell pour HP OneView afin de requêter des alertes sur les appliances HP OneView avec la possibilité de changer leur état en Cleared.

Pour rappel, HP OneView est l’outil de management et de centralisation de la configuration des des systèmes convergés HP. Il utilise des appliances dédiés a la gestion des materiels.

Au passage, Un management pack HP OneView pour SCOM est fourni afin de superviser les appliances et les materiels gérés.

En surcouche des API REST fourni par HP, il existe un projet d’API pour Powershell et Python permettant de manipuler plus facilement les fonctionnalités de l’interface OneView.

Le site pour l’API Powershell est disponible via https://github.com/HewlettPackard/POSH-HPOneView

Le script est un exemple de connexion et de récupération multi-critère.

 

############################################################################## # SCRIPT DE RECUPERATION DES ALERTES D'UNE APPLIANCE HPONEVIEW ET MISE EN ETAT CLEARED # author: cjourdan # PARAMETRES: # $ApplianceName: Nom de l'appliance # $RessourceName: Nom de la ressource (Server,Enclosure ...). # $DomainName: Domaine AD. # $AlertSeverity: Critical, Warning, OK, Unknown, Disabled # $AlertState: Active, Locked, Cleared, Pending, Running, Completed, Interrupted, Error, Warning, Terminated, Killed. # $DescInclude: Chaine de caractère dans la champ Description a inclure dans la recherche. # $DescExclude: Chaine de caractère dans la champ Description a exclure de la recherche. # $DayOffset = Recuperer les alertes plus recente que J-DayOffset. # Apres Recuperation des alertes, le script demande validation pour mettre les alertes en état Cleared Param( [Parameter(Mandatory=$false)] $ApplianceName = "MyAppliance", [Parameter(Mandatory=$false)] # Server,Enclosure ... $RessourceName = "MyResource", [Parameter(Mandatory=$false)] $DomainName = "MyDomain", [Parameter(Mandatory=$false)] $AlertSeverity = "Critical", [Parameter(Mandatory=$false)] $AlertState = "Cleared", $DescInclude = "*", $DescExclude = "azerty", $DayOffset = 2 ) $user = Read-Host -Prompt "Enter MyDomain Credential without Domain" $passwd = Read-Host -Prompt "Password" -AsSecureString if (-not (get-module HPOneview.200)) { Import-Module HPOneView.200 } # Connexion a l'appliance OneView if (-not($global:ConnectedSessions)) { Connect-HPOVMgmt -Hostname $ApplianceName -UserName $user -Password $passwd -AuthLoginDomain $DomainName } write-host -BackgroundColor White -ForegroundColor Blue "APPLIANCE ONEVIEW: $ApplianceName"`n # NB: Preciser au minimum un filtre de recherche avant le '|' afin de reduire le temps de recuperation des alertes Try { $Alerts = Get-HPOVAlert -ApplianceConnection $ApplianceName -Severity $AlertSeverity | Where-Object {$_.AlertState -eq $AlertState ` -AND $_.associatedresource -like "*$RessourceName*" ` -AND $_.description -like "*$DescInclude*" ` -AND $_.description -notlike "*$DescExclude*"` -AND $([datetime]$_.created) -gt $(get-date).AddDays(-$DayOffset) } $FormAlerts = foreach ($alert in $Alerts) { Write-output "DESCRIPTION: "$alert.description"" ; Write-Output "SEVERITY: "$alert.severity"" ; Write-Output "STATE: "$alert.alertState"" ; Write-Output "CREATED: "(get-date -format G $alert.Created)"" ; Write-Output "CLEARED: "(get-date -format G $alert.clearedtime)"" ; Write-Output "RESSOURCE_NAME: "$alert.associatedresource.resourcename"" ; Write-Output "APPLIANCE: "$alert.ApplianceConnection.Name"" ; Write-Output "" ; Write-Output "*******************" ; Write-Output "" } write-host -BackgroundColor White -ForegroundColor Blue "CRITERES DE RECHERCHE: Resource: $RessourceName / Severity: $AlertSeverity / Status: $AlertState / a inclure: $DescInclude / a exclure: $DescExclude / Plus recentes que: J-$DayOffset"`n $count=$Alerts | Measure-Object | select count -ExpandProperty count write-host -BackgroundColor White -ForegroundColor Blue "NOMBRE D ALERTES: $count" `n $FormAlerts } Catch { Write-Error -ErrorRecord $_ -ErrorAction Stop } $answer = Read-Host -Prompt "VOULEZ VOUS MODIFIER L'ETAT DES CES ALERTES EN ETAT 'CLEARED' ?: Y/N" switch($answer) { "Y" {"MISE EN ETAT CLEARED"} "N" {"AUCUNE ACTION" ; exit} default {"MAUVAISE REPONSE - AUCUNE ACTION" ; exit} } # Clear Alerts Try { $updatedAlert = $Alerts | set-HPOVAlert -Cleared } Catch { Write-Error -ErrorRecord $_ -ErrorAction Stop } $updatedAlert Write-Host -ForegroundColor Green "MISE EN ETAT CLEARED TERMINEE SANS ERREUR !"