PI Services

Le blog des collaborateurs de PI Services

SCOM - Script - Supprimer un agent de la console en fonction de la valeur d'une ou plusieurs propriété d'une classe

Le script ci-dessous propose le scenario ou l'on doit automatiser la suppression d'un agent de la console (pas une desinstallation) en fonction de la valeur d'une ou plusieurs propriétés de l'instance d'une classe pour ce/ces agents.

Ceci peut permettre par exemple dans la cas de la présence d'une classe étendue (avec vos propres propriétés issues par exemple d'un outil tiers) de decommissionner un ou plusieurs agents automatiquement, selon la valeur de ces propriétés (Dans l'exemple inscrit par defaut dans les paramètres, on cherche la valeur 'Useless' ou 'Deprecated' de la propriété 'Usage' de la classe 'MyClass')

 

RemoveAgentUponPropertyVal.ps1 (10,67 kb)

 

## RemoveAgentUponPropertyVal.ps1
## SCOM - REMOVE AGENT(S) FROM CONSOLE THAT HAVE SPECIFIC VALUES IN ONE OR MORE CLASS PROPERTY.
## AUTHOR: C.JOURDAN
## Version: 1.0

##  PARAMETERS
##  $MS: Target Management Server
##  $ObjectClass: Display Name of Target Class
##  $FirstProperty: name of class property
##  $FirstPropVal: multi value possible of $FirstProperty
##  $ThreshNotDelete: Nb of found computers to delete over which we only warn (NO AUTOMATIC DELETE)

## NOTES: $ThreshNotDelete PARAMETER IS A SECURITY OPTION TO AVOID DELETION OF TWO MANY AGENTS. BE SURE OF THE APPLIED CRITERIAS BEFORE UNLOCK THAT! 


#PARAMETERS
Param(
[Parameter(Mandatory=$false)]
$MGroup,
[Parameter(Mandatory=$false)]
$MS='localhost',
[Parameter(Mandatory=$false)]
$ObjectClass = 'MyClass',
[Parameter(Mandatory=$false)]
$FirstProperty='Usage',
[Parameter(Mandatory=$false)]
$FirstPropVal="^.*(Useless|Deprecated).*$",
<# -- ADDITIONAL PROPERTIES FROM $ObjectClass INSTANCE -- SEE CLASS INSTANCE RETRIEVE SECTION
[Parameter(Mandatory=$false)]
$SecondProperty='Prop2',
[Parameter(Mandatory=$false)]
$SecondPropVal='Value2'
#>
[Parameter(Mandatory=$false)]
$ThreshNotDelete = 10
)

#ScriptName
$ScriptName = "RemoveAgentUponPropertyVal.ps1"


#FUNCTIONS

# NewEventSource
# Check of a source existance  in the 'operation manager' eventlog that match the script name, to log some events.
         Function NewEventSource 
         { 
         if(!(Test-Path "HKLM:\SYSTEM\CurrentControlSet\services\eventlog\Operations Manager\$ScriptName")) 
         { 
         New-EventLog -LogName "Operations Manager" -Source $ScriptName 
         }
         } 


# DeleteSCOMAgent
# Remove agent from SCOM Console.
Function DeleteSCOMAgent 
{
Param(
  [string[]]$AgentComputerName,
  [string]$MSServer
)

[System.Reflection.Assembly]::Load("Microsoft.EnterpriseManagement.Core, Version=7.0.5000.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")
[System.Reflection.Assembly]::Load("Microsoft.EnterpriseManagement.OperationsManager, Version=7.0.5000.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")



function New-Collection ( [type] $type ) 
{
	$typeAssemblyName = $type.AssemblyQualifiedName;
	$collection = new-object "System.Collections.ObjectModel.Collection``1[[$typeAssemblyName]]";
	return ,($collection);
}




# Connect to management group
Write-output "Connecting to management group"

$ConnectionSetting = New-Object Microsoft.EnterpriseManagement.ManagementGroup($MSServer)
$admin = $ConnectionSetting.GetAdministration()


Write-output "Getting agent managed computers"
$agentManagedComputers = $admin.GetAllAgentManagedComputers()

# Get list of agents to delete
foreach ($name in $AgentComputerName) 
{
    Write-output "Checking for $name"
    foreach ($agent in $agentManagedComputers)
    {
        if ($deleteCollection -eq $null) 
        {
            $deleteCollection = new-collection $agent.GetType()
        }

        
        if (@($agent.PrincipalName -eq $name))
        {
	    Write-output "Matched $name"
            $deleteCollection.Add($agent)
            break
        }
    }
}

if ($deleteCollection.Count -gt 0) 
{
    Write-output "Deleting agents"
    $admin.DeleteAgentManagedComputers($deleteCollection)
    if($?){
           $Script:result="Agents deleted"
           Write-Output $result
          }
    Else  {
           $result="Error during deletion of one ore more agent"
           Write-Output $result
          }
}

Else
    {
    $result="No Agent found to delete"
    Write-Output $result
    }


}




#END FUNCTIONS


#Log of script execution 
NewEventSource 
write-eventlog -logname "Operations Manager" -Source $ScriptName -EventID 1000 -Message "Execution du script $ScriptName" -EntryType Information 



#Import of SCOM Powershell module
try
{
Import-Module -Name OperationsManager -ErrorAction stop
}
catch
{
write-host -ForegroundColor red "Error during import of SCOM PS Module"
NewEventSource 
write-eventlog -logname "Operations Manager" -Source $ScriptName -EventID 1001 -Message "Error during import of SCOM PS Module" -EntryType Error 
exit 1 
}



#Connection to management group $MGroup
try
{
New-SCOMManagementGroupConnection -ComputerName $MS
}
catch
{
write-host -ForegroundColor red "Error during connection to MS $MS"
NewEventSource 
write-eventlog -logname "Operations Manager" -Source $ScriptName -EventID 1002 -Message "Error during connection to MS $MS" -EntryType Error 
exit 1 
}


# Get $ObjectClass Class
$Class = Get-SCOMClass -displayname $ObjectClass | Where-Object {$_.PropertyCollection -match "^.*($FirstProperty|$SecondProperty).*$"} -ErrorAction stop    ## -- WE CHECK THAT THE TARGET CLASS REALLY HOLD THE WANTED PROPERTIES
if (!($Class))
{
$message = "ERROR DURING RETRIEVE OF '$ObjectClass' CLASS. CHECK THAT CLASS EXIST OR THAT THE PROPERTIES YOU WANT EXIST IN THIS CLASS"
write-host -ForegroundColor red $message
NewEventSource 
write-eventlog -logname "Operations Manager" -Source $ScriptName -EventID 1003 -Message $message -EntryType Error 
exit 1 
}




# Get Computers that have $FirstProperty value as: $FirstPropVal 
try
{
$TargetComp = $Class | Get-SCOMClassInstance | Where-Object {
$_."[$($Class.Name)].$FirstProperty".value -match $FirstPropVal -OR $_.$FirstProperty -match $FirstPropVal`               ##-- DIFFERENT COMBINATION (THE "[$($Class.Name)]" SYNTAX IS TO INCLUDE CASE OF A NOTE PROPERTY
#-AND $_."[$($Class.Name)].$SecondProperty".value -eq $SecondPropVal -OR $_.$SecondProperty -eq $SecondPropVal`     ##-- ADDITIONAL POTENTIAL PROPERTIES (SEE SCRIPT PARAMS)
} -ErrorAction Stop

#$TargetComp = $Class | Get-SCOMClassInstance | Where-Object {                                                       ## -- TO TEST UNFOUND COMPUTER SCENARIO
#$_."[$($Class.Name)].$FirstProperty".value -eq "azerty" -OR $_.$FirstProperty -eq "azerty"`                        ## -- TO TEST UNFOUND COMPUTER SCENARIO
#} -ErrorAction Stop                                                                                                ## -- TO TEST UNFOUND COMPUTER SCENARIO

}
catch
{
$message = "Error during retrieve of '$ObjectClass' instances that have $FirstProperty : $FirstPropVal"
write-host -ForegroundColor red $message
NewEventSource 
write-eventlog -logname "Operations Manager" -Source $ScriptName -EventID 1004 -Message $message -EntryType Error 
exit 1 
}


# Analyse the content of $TargetComp
switch($TargetComp.Count)
{
{$_ -lt 1}                  {            
                            $message = "NO AGENT TO REMOVE"
                            Write-Host -F Blue -B White $message
                            NewEventSource 
                            write-eventlog -logname "Operations Manager" -Source $ScriptName -EventID 1005 -Message $message -EntryType Information 
                            }


{$_ -ge 1 -AND $_ -le $ThreshNotDelete} ## -- SECURITY OPTION TO AVOID DELETION OF TWO MANY AGENTS. BE SURE OF THE APPLIED CRITERIAS BEFORE UNLOCK THAT!
                            {
                            $message = "FOLLOWING AGENTS WILL BE REMOVED:"
                            Write-Host -F Yellow $message
                            $TargetComp.displayname
                                                            
                                DeleteSCOMAgent -AgentComputerName $TargetComp.displayname -MSServer $MS
                                #$result
                                switch($result)
                                    {
                                    "Agents deleted" 
                                                                                        {
                                                                                            $message = "FOLLOWING AGENTS HAS BEEN REMOVED FROM SCOM CONSOLE SINCE THEIR $FirstProperty IS EQUAL: $FirstPropVal . $($TargetComp.displayname)"
                                                                                            NewEventSource 
                                                                                            write-eventlog -logname "Operations Manager" -Source $ScriptName -EventID 1006 -Message $message -EntryType Information 
                                                                                        }
                                    
                                    "Error during deletion of one ore more agent" 
                                                                                        {
                                                                                            $message = "ERROR DURING DELETION OF ONE OR MORE AGENT! MANUAL CHECK REQUIRED"
                                                                                            NewEventSource 
                                                                                            write-eventlog -logname "Operations Manager" -Source $ScriptName -EventID 1007 -Message $message -EntryType Warning
                                                                                        } 

                                    "No Agent found to delete" 
                                                                                        {
                                                                                            $message = "NO AGENT FOUND TO DELETE BY DeleteSCOMAgent FUNCTION! MANUAL CHECK REQUIRED"
                                                                                            NewEventSource 
                                                                                            write-eventlog -logname "Operations Manager" -Source $ScriptName -EventID 1008 -Message $message -EntryType Warning
                                                                                        } 


                                    
                                
                                    
                                
                            
                                }

                            }

{$_ -gt $ThreshNotDelete}                 {
                            $message = "WARNING: NUMBER OF AGENTS TO REMOVE IS GREATER THAN 10 ! MANUAL CHECK REQUIRED"  ## -- SECURITY OPTION TO AVOID DELETION OF TWO MANY AGENTS. BE SURE OF THE APPLIED CRITERIAS BEFORE UNLOCK THAT!
                            Write-Host -F red $message
                            $TargetComp.displayname
                            NewEventSource 
                            write-eventlog -logname "Operations Manager" -Source $ScriptName -EventID 1009 -Message $message -EntryType Warning
                            }


}



 

 

 

 

Ajouter un commentaire

Loading