PI Services

Le blog des collaborateurs de PI Services

SCOM - Script - Supprimer ou Mettre en mode maintenance un/des agent selon la valeur d'une propriété (Nouvelle version)

Le script suivant est une nouvelle version d'un script récemment proposé. Ont été rajouté le choix entre suppression et mode maintenance (on verifie aussi que la machine est déjà en mode maintenance)

 

DeleteOrMaintenanceAgentUponPropertyValue.ps1 (14,85 kb)

 

## DeleteOrMaintenanceAgentUponPropertyValue.ps1
## SCOM - REMOVE FROM CONSOLE OR PUT IN MAINTENANCE MODE, AGENT(S) THAT HAVE SPECIFIC VALUES IN ONE OR MORE CLASS PROPERTY.
## AUTHOR: C.JOURDAN
## Version: 1.1

##  PARAMETERS
##  $MS: Target Management Server
##  $ObjectClass: Display Name of Target Class
##  $FirstProperty: name of class property
##  $FirstPropVal: multi value possible of $FirstProperty
##  $Action: DELETE or MAINTENANCE
##  $MaintenanceDuration: Nb of minutes for Maintenance Mode
##  $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="MyMS",
[Parameter(Mandatory=$false)]
$ObjectClass="MyClass",
[Parameter(Mandatory=$false)]
$FirstProperty='MyProperty',
[Parameter(Mandatory=$false)]
$FirstPropVal="^.*(AZERTY|QWERTY).*$",
<# -- ADDITIONAL PROPERTIES FROM $ObjectClass INSTANCE -- SEE CLASS INSTANCE RETRIEVE SECTION
[Parameter(Mandatory=$false)]
$SecondProperty='Prop2',
[Parameter(Mandatory=$false)]
$SecondPropVal='Value2'
#>
[Parameter(Mandatory=$false)]
$Action = "Maintenance",
[Parameter(Mandatory=$false)]
$MaintenanceDuration = 30,
[Parameter(Mandatory=$false)]
$ThreshNotDelete = 10
)

#ScriptName
$ScriptName = "DeleteOrMaintenanceAgentUponPropertyValue.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.name""

$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
    }


}


Function SetMM
{
# Function SetMM 
########################################################################
# 
#
[CmdletBinding()]

param(
  [string]$HostToMM,
  [string]$Duration
)

$startTime = [DateTime]::Now
$endTime = $startTime.AddMinutes($Duration)

    # Get "Microsoft.Windows.Computer" Class
    $Class = get-SCOMclass | where-object {$_.Name -eq "Microsoft.Windows.Computer"};

    $Instance = Get-SCOMClassInstance -Class $Class | Where-Object {$_.Displayname -like "$HostToMM*"};
    
    Start-SCOMMaintenanceMode -Instance $Instance -Reason "PlannedOther" -EndTime $endTime -Comment "PLANNED BY SCOM AGENT REMOVER" -ErrorAction Stop
    
    
}



#END FUNCTIONS



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


# Check if $Action is valid
if ($Action -notmatch "^delete|maintenance$")
    {
    $message = "NO VALID ACTION HAS BEEN CHOOSED - POSSIBLE VALUE: `"DELETE`" OR `"MAINTENANCE`""
    write-host -ForegroundColor Yellow $message
    NewEventSource 
    write-eventlog -logname "Operations Manager" -Source $ScriptName -EventID 1000 -Message $message -EntryType Warning
    exit 1
    }



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



#Connection to management group $MGroup
try
{
New-SCOMManagementGroupConnection -ComputerName $MS
}
catch
{
$message = "ERROR DURING CONNECTION TO $MS"
write-host -ForegroundColor red $message
NewEventSource 
write-eventlog -logname "Operations Manager" -Source $ScriptName -EventID 1002 -Message $message -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. (CRITERIAS: Class=`"$ObjectClass`" - Property=`"$FirstProperty`" - Value=`"$FirstPropVal`")"
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 CLASS INSTANCES (CRITERIAS: Class=`"$ObjectClass`" - Property=`"$FirstProperty`" - Value=`"$FirstPropVal`")"
write-host -ForegroundColor red $message
NewEventSource 
write-eventlog -logname "Operations Manager" -Source $ScriptName -EventID 1004 -Message $message -EntryType Error 
exit 1 
}




switch($Action)
{
"Delete" {


# Analyse the content of $TargetComp
switch($TargetComp.Count)
{
{$_ -lt 1}                  {            
                            $message = "NO AGENT TO REMOVE (CRITERIAS: Class=`"$ObjectClass`" - Property=`"$FirstProperty`" - Value=`"$FirstPropVal`")"
                            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 (CRITERIAS: Class=`"$ObjectClass`" - Property=`"$FirstProperty`" - Value=`"$FirstPropVal`") :`n "
                                                                                            $message += $TargetComp | foreach {$_.DisplayName ;"`n"}
                                                                                            write-host $message
                                                                                            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 (CRITERIAS: Class=`"$ObjectClass`" - Property=`"$FirstProperty`" - Value=`"$FirstPropVal`") "
                                                                                            write-host $message
                                                                                            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 - MANUAL CHECK REQUIRED (CRITERIAS: Class=`"$ObjectClass`" - Property=`"$FirstProperty`" - Value=`"$FirstPropVal`")"
                                                                                            write-host $message
                                                                                            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
                            }


}


         }


"Maintenance" {

#Clear-Variable message

    If ($TargetComp.Count -ge 1)
        {

        foreach ($target in $TargetComp)
            {
            If (Get-SCOMMaintenanceMode -Instance $target)
                {
                #$message += "`n$target IS ALREADY IN MAINTENANCE MODE"
                $AlreadyInMM += "$target`n"
                }
            Else
                {
                SetMM -HostToMM $target -Duration $MaintenanceDuration
                $PutInMM += "$target`n" 
                }
            }
                       

            $message = "`nFOLLOWING AGENTS HAS BEEN SET IN MAINTENANCE MODE (CRITERIAS: Class=`"$ObjectClass`" - Property=`"$FirstProperty`" - Value=`"$FirstPropVal`") :`n"
            $message += $PutInMM
            $message += "`n`nFOLLOWING AGENTS ARE ALREADY IN MAINTENANCE MODE (CRITERIAS: Class=`"$ObjectClass`" - Property=`"$FirstProperty`" - Value=`"$FirstPropVal`") :`n"
            $message += $AlreadyInMM
            write-host $message
            NewEventSource 
            write-eventlog -logname "Operations Manager" -Source $ScriptName -EventID 1010 -Message $message -EntryType Information 
         }
        
    Else
        {
        $message = "NO AGENT TO PUT IN MAINTENANCE MODE HAS BEEN FOUND. (CRITERIAS: Class=`"$ObjectClass`" - Property=`"$FirstProperty`" - Value=`"$FirstPropVal`")"
        write-host $message
        NewEventSource 
        write-eventlog -logname "Operations Manager" -Source $ScriptName -EventID 1011 -Message $message -EntryType Information
        }
    }


default {

        $message = "No action has been choosed. Possible value: `"Delete`" (Delete Agent from console) or `"Maintenance`" (Put corresponding computer in Maintenance Mode)"
        write-host -ForegroundColor red $message
        NewEventSource 
        write-eventlog -logname "Operations Manager" -Source $ScriptName -EventID 1012 -Message $message -EntryType Error 
        exit 1 
        }

}

 

Ajouter un commentaire

Loading