PI Services

Le blog des collaborateurs de PI Services

SCOM - Script de mode maintenance depuis une liste

Le script ci-dessous est une version un peu avancée avec des fonctions de log et de vérification.

SetInstanceFromFileInMM.txt (5,99 kb)

 

# SET MULTIPLE CLASS INSTANCE FROM LIST, IN MAINTENANCE MODE.

#Parametres
Param(
$ClassName="Microsoft.Windows.Computer", # Name of Class (Not DisplayName to avoid system language differences) 
$MS= "MyMS.Mydomain.com", # Target Management Server
$cred = $(Get-Credential),
$HostFilePath="C:\HostMM.txt", # List of Host to put in Maintenance Mode
$Duration="10", # Duration in minutes (min: 5 minutes)
$LogPath = "C:\MMlog.txt" # Path of Log file
)



function Write-Log 
{ 
    [CmdletBinding()] 
    Param 
    ( 
        [Parameter(Mandatory=$true, 
                   ValueFromPipelineByPropertyName=$true)] 
        [ValidateNotNullOrEmpty()] 
        [Alias("LogContent")] 
        [string]$Message, 
 
        [Parameter(Mandatory=$false)] 
        [Alias('LogPath')] 
        [string]$Path=$LogPath, 
         
        [Parameter(Mandatory=$false)] 
        [ValidateSet("Error","Warn","Info")] 
        [string]$Level="Info", 
         
        [Parameter(Mandatory=$false)] 
        [switch]$NoClobber 
    ) 
 
    Begin 
    { 
        # Set VerbosePreference to Continue so that verbose messages are displayed. 
        $VerbosePreference = 'Continue' 
    } 
    Process 
    { 
         
        # If the file already exists and NoClobber was specified, do not write to the log. 
        if ((Test-Path $Path) -AND $NoClobber) { 
            Write-Error "Log file $Path already exists, and you specified NoClobber. Either delete the file or specify a different name." 
            Return 
            } 
 
        # If attempting to write to a log file in a folder/path that doesn't exist create the file including the path. 
        elseif (!(Test-Path $Path)) { 
            Write-Verbose "Creating $Path." 
            $NewLogFile = New-Item $Path -Force -ItemType File 
            } 
 
        else { 
            # Nothing to see here yet. 
            } 
 
        # Format Date for our Log File 
        $FormattedDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss" 
 
        # Write message to error, warning, or verbose pipeline and specify $LevelText 
        switch ($Level) { 
            'Error' { 
                Write-Error $Message 
                $LevelText = 'ERROR:' 
                } 
            'Warn' { 
                Write-Warning $Message 
                $LevelText = 'WARNING:' 
                } 
            'Info' { 
                Write-Verbose $Message 
                $LevelText = 'INFO:' 
                } 
            } 
         
        # Write log entry to $Path 
        "$FormattedDate $LevelText $Message" | Out-File -FilePath $Path -Append 
    } 
    End 
    { 
    } 
}


# Initiate Log File
$message = "------ START OF MAINTENANCE MODE LOG ------`n`n"
Write-Log -Message $message -Path $LogPath -Level Info -ErrorAction SilentlyContinue


#Check that Host list file exist
if (!(Test-Path -Path $HostFilePath))
    {
    $message = "Unable to find Host list file`n"
    write-host -ForegroundColor red $message
    Write-Log -Message $message -Path $LogPath -Level Error -ErrorAction SilentlyContinue
    exit 1
    }


# Store content of file
$HostList = Get-Content -Path $HostFilePath


#Import of SCOM module
try
{
Import-Module -Name OperationsManager -ErrorAction stop
}
catch
{
$message = "Error during import of SCOM PS module`n"
write-host -ForegroundColor red $message
Write-Log -Message $message -Path $LogPath -Level Error -ErrorAction SilentlyContinue
exit 1
}


#Connection to management server $MS
try
{
New-SCOMManagementGroupConnection -ComputerName $MS -Credential $cred
}
catch
{
$message = "Error during connection to $MS`n"
write-host -ForegroundColor red $message
Write-Log -Message $message -Path $LogPath -Level Error -ErrorAction SilentlyContinue
exit 1
}
 

# Set Start/End Time upon Duration 
$startTime = [DateTime]::Now
$endTime = $startTime.AddMinutes($Duration)


# Get the class
$Class = Get-SCOMClass | where-object {$_.Name -eq $ClassName} -ErrorAction Stop

If ($Class -eq $null)
    {
    $message = "Unable to find `"$ClassName`" Class`n"
    write-host -ForegroundColor red $message
    Write-Log -Message $message -Path $LogPath -Level Error -ErrorAction SilentlyContinue
    exit 1
    }



# Get the instances where displayname match content of $HostList
$Instances = Get-SCOMClassInstance -Class $Class | Where-Object {`
$_.Displayname -in $HostList 
} -ErrorAction Stop

If ($Instances -eq $null)
    {
    $message = "Unable to find instances of `"$ClassName`" Class`n"
    write-host -ForegroundColor red $message
    Write-Log -Message $message -Path $LogPath -Level Error -ErrorAction SilentlyContinue
    exit 1
    }



# Put in Maintenance Mode
$message = "Putting following instances in Maintenance Mode for $Duration minutes...:`n $($Instances | foreach {"$_;`n"})"
write-host $message
Write-Log -Message $message -Path $LogPath -Level Info -ErrorAction SilentlyContinue

    
$Instances | foreach {`
    try
    {
    $message = "`nSetting Maintenance Mode on `"$_`"..."
    write-host $message
    Write-Log -Message $message -Path $LogPath -Level Info -ErrorAction SilentlyContinue
    Start-SCOMMaintenanceMode -Instance $_ -Reason "PlannedOther" -EndTime $endTime -Comment "MM of $_" -ErrorAction Stop
    }
    catch
    {
    $message = "Error setting Maintenance Mode on `"$_`""
    write-host -ForegroundColor red $message
    Write-Log -Message $message -Path $LogPath -Level Error -ErrorAction SilentlyContinue
    }
}
    

# Check and log Maintenance Mode
$message = "Checking Maintenance Mode..."
Write-Log -Message $message -Path $LogPath -Level Info -ErrorAction SilentlyContinue

$Instances | foreach {`
$message = Get-SCOMMaintenanceMode -Instance $_ | foreach {"COMMENT: $($_.Comments) -- START:$($_.StartTime) -- END:$($_.ScheduledEndTime) -- REASON:$($_.Reason) -- USER:$($_.User)`n" } 
Write-Log -Message $message -Path $LogPath -Level Info -ErrorAction SilentlyContinue

}




    

 

 

Ajouter un commentaire

Loading