SCOM Maintenance Mode Scheduling Solution (Optimized and Free)

When it comes to scheduling maintenance mode in SCOM you can probably find quite a few solutions posted on Internet. This blogpost is presenting yet another (free) solution. Who knows, perhaps you’ll appreciate the simplicity of it…

My solution is leveraging only basic SCOM features: Computer Groups, System.Scheduler data source module type and VSAE snippets. In a few minutes you will be able to create your own Management Pack that will do the Maintenance Mode scheduling for you. From then on, you’ll just have to maintain this Management Pack in a very convenient way, as easy as (re)importing a csv file. Plus you’ll have to author some Computer Groups and you’re done.

Here are the steps:

1/ Using Visual Studio create a new Project (Operations Manager 2012 R2 Management Pack): call it MaintModeScheduling

2/ You will need a custom Write Action Module Type so create a MP Fragment for that like the one presented below:

<ManagementPackFragment SchemaVersion="2.0" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <TypeDefinitions>
    <ModuleTypes>
      <WriteActionModuleType ID="MaintModeScheduling.StartMMForGroup.WA" Accessibility="Public" >
        <Configuration>
          <xsd:element name="ComputerGroupDisplayName" type="xsd:string" minOccurs="1" maxOccurs="1"/>
          <xsd:element name="ForHowLongInMin" type="xsd:integer" minOccurs="1" maxOccurs="1"/>
          <xsd:element name="Comment" type="xsd:string" minOccurs="1" maxOccurs="1"/>
        </Configuration>
        <OverrideableParameters>
        </OverrideableParameters>
        <ModuleImplementation>
          <Composite>
            <MemberModules>
              <WriteAction ID="WA" TypeID="Windows!Microsoft.Windows.PowerShellPropertyBagWriteAction" >
                <ScriptName>Start-SCOMMaintModeForGroup.ps1</ScriptName>
                <ScriptBody>$IncludeFileContent/Scripts/Start-GroupMaintMode.ps1$</ScriptBody>
                <SnapIns>
                </SnapIns>
                <Parameters>
                  <Parameter>
                    <Name>ComputerGroupDisplayName</Name>
                    <Value>$Config/ComputerGroupDisplayName$</Value>
                  </Parameter>
                  <Parameter>
                    <Name>ForHowLongInMin</Name>
                    <Value>$Config/ForHowLongInMin$</Value>
                  </Parameter>
                  <Parameter>
                    <Name>Comment</Name>
                    <Value>$Config/Comment$</Value>
                  </Parameter>
                </Parameters>
                <TimeoutSeconds>300</TimeoutSeconds>
              </WriteAction>
            </MemberModules>
            <Composition>
              <Node ID="WA"/>
            </Composition>
          </Composite>
        </ModuleImplementation>
        <InputType>System!System.BaseData</InputType>
      </WriteActionModuleType>
    </ModuleTypes>
  </TypeDefinitions>
</ManagementPackFragment>

3/ Add a new folder to the solution called Scripts; then add a PowerShell script file resource to this folder, name the script “Start-GroupMaintMode.ps1” and copy the following content to the file

<#  .SYNOPSIS Places all members of a SCOM Computer Group in maintenance mode. .DESCRIPTION Places all members of a SCOM Computer Group in maintenance mode. .EXAMPLE  Start-GroupMaintMode.ps1 -ComputerGroupDisplayName "GroupA" -ForHowLongInMin 10 -Comment "Testing Maintenance Mode" -Verbose  Puts all Members of the "GroupA" Group in Maintenance Mode for 10 minutes with Comment "Testing Maintenance Mode". Adding Verbose information. .PARAMETER ComputerGroupDisplayName = The SCOM Computer Group name for which members you want to put in Maintenance Mode.  .PARAMETER ForHowLongInMin = The Maintenance Mode Interval .PARAMETER Comment = The Maintenance Mode Comment #>            

[CmdletBinding(SupportsShouldProcess=$true)]

param([string[]]$ComputerGroupDisplayName,[int]$ForHowLongInMin,[string]$Comment)

$Reason = "PlannedApplicationMaintenance"

$MS = gc env:computername
$ScriptName = "Start-GroupMaintMode.ps1"
$LogEventID = 509

$evt = New-Object System.Diagnostics.EventLog("Operations Manager")
$evt.Source = "MMScheduling"
$infoevent  = [System.Diagnostics.EventLogEntryType]::Information
$warnevent  = [System.Diagnostics.EventLogEntryType]::Warning
$errorevent = [System.Diagnostics.EventLogEntryType]::Error

Write-Verbose "Script $ScriptName started on $MS"
$evt.WriteEntry("Script $ScriptName started on $MS",$infoevent,$LogEventID)

$ModuleImportError = $false
Try
{
	$setupKey = Get-Item -Path "HKLM:\Software\Microsoft\Microsoft Operations Manager\3.0\Setup"
	$installDirectory = $setupKey.GetValue("InstallDirectory") | Split-Path
	$psmPath = $installdirectory + ‘\Powershell\OperationsManager\OperationsManager.psm1’

	Import-Module $psmPath

	$conn = (New-SCOMManagementGroupConnection –ComputerName $MS)
}
Catch [system.exception]
{
	Write-Verbose "Errors detected while importing module OperationsManager on $MS; $error"
	$evt.WriteEntry("Errors detected while importing module OperationsManager on $MS; $error",$errorevent,$LogEventID)
	$ModuleImportError = $true
}

If (!$ModuleImportError)
{
	$Groups = Get-SCOMGroup -DisplayName $ComputerGroupDisplayName

	if($Groups -ne $null)
	{
		foreach ($Group in $Groups)
		{
			If ($Group.InMaintenanceMode -eq $false)
			{
				Write-Verbose "Starting Maintenance Mode for $Group.DisplayName"
				$evt.WriteEntry("Starting Maintenance Mode for $Group.DisplayName",$infoevent,$LogEventID)
				$Group.ScheduleMaintenanceMode([datetime]::Now.touniversaltime(), ([datetime]::Now).addminutes($ForHowLongInMin).touniversaltime(), "$Reason", "$Comment" , "Recursive")
			}
		}
	}
}

4/ Add a snippet template to the solution (Right click on solution, Add / New Item/ Management Pack / Code / Snippet Template); name it StartMMForGroup.templatesnippet; copy/paste the following MP fragment to this snippet template:

<ManagementPackFragment SchemaVersion="2.0">
  <Monitoring>
    <Rules>
      <Rule ID="#text('Rule Id')#" Target="SC!Microsoft.SystemCenter.RootManagementServer" Enabled="#text('Enabled')#" ConfirmDelivery="false" Remotable="true" Priority="Normal" DiscardLevel="100">
        <Category>Operations</Category>
        <DataSources>
          <DataSource ID="DS" TypeID="System!System.Scheduler">
            <Scheduler>
              <WeeklySchedule>
                <Windows>
                  <Daily>
                    <Start>#text('StartTime')#</Start>
                    <End>#text('StartTime')#</End>
                    <DaysOfWeekMask>#text('DaysOfWeekMask')#</DaysOfWeekMask>
                  </Daily>
                </Windows>
              </WeeklySchedule>
              <ExcludeDates />
            </Scheduler>
          </DataSource>
        </DataSources>
        <WriteActions>
          <WriteAction ID="WA" TypeID="MaintModeScheduling.StartMMForGroup.WA">
            <ComputerGroupDisplayName>#text('ComputerGroupDisplayName')#</ComputerGroupDisplayName>
            <ForHowLongInMin>#text('ForHowLongInMin')#</ForHowLongInMin>
            <Comment>#text('Comment')#</Comment>
          </WriteAction>
        </WriteActions>
      </Rule>
    </Rules>
  </Monitoring>
  <LanguagePacks>
    <LanguagePack ID="ENU" IsDefault="true">
      <DisplayStrings>
        <DisplayString ElementID="#text('Rule Id')#">
          <Name>#text('Rule Id')#</Name>
        </DisplayString>
      </DisplayStrings>
    </LanguagePack>
  </LanguagePacks>
</ManagementPackFragment>

5/ Add snippet data to the solution (Right click on solution, Add / New Item / Management Pack / Templates / Snippet Data); call it StartMMForGroup.mpsd; then press the “Select snippet type” button and you’ll have the only option “StartMMForGroup”.

Add few items according to your needs. I think the parameter names are self-explanatory. In case in doubt what to enter for DaysOfWeekMask please refer to the PublicSchedulerType complex data type (https://msdn.microsoft.com/en-us/library/ee692976.aspx). If it’s more convenient you can Import from CSV file the data at this step.

Note that Visual Studio will perform syntax checking at this step for the data that you enter.

6/ Build your solution and import the MP. The rules in the MP will take care of the Maintenance Mode Scheduling exactly as you wrote the instructions in the snippet data. Maintain the snippet data to reflect the needs of Maintenance Mode Scheduling in your organization (and don’t forget to combine this with accurate Computer Groups membership definitions)

Enjoy…

Advertisements

One response to “SCOM Maintenance Mode Scheduling Solution (Optimized and Free)

  1. Pingback: System Center Operations Manager – Tech Guide

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: