Skip to content
adatum
  • Home
  •  About adatum
  •  Learn Azure Bicep
  •  SCOM Web API
Automation

SCOM 2016 Schedule Maintenance Script

  • 09/11/201607/01/2025
  • by Martin Ehrnst

With Operation Manager 2016 we finally have the ability to Schedule maintenance for Objects.
Doing that in GUI is pretty straitght forward, altough i have seen some blog post on issues With conflicting maintenance schedules. Besides scheduling maintenance mode in the GUI we have gotten some New PS CMDlet’s to manage maintance schedules.

One of them are New-SCOMMaintenanceSchedule.

Based on this i have created the following script wich will take parameters for servername, comments, start and end date before creating a New maintenance Schedule With the supplied server Objects (Linux/Windows)

Feel free to use and please give me feedback on improvements and bugs. Beware that this Version has some limitations and little error handling.

<#

.SYNOPSIS
    System Center Operations Manager 2016 Schedule maintenance mode script.

.DESCRIPTION
    Adding a SCOM 2016 maintencance shedule to specified servers. Works with Linux and Windows servers.

.EXAMPLE
    New-SCOMServerMaintenanceSchedule.ps1 -ServerName SERVER01 -start '01/01/2017 18:30' -end '02/01/2017' -comment "your comment"

    Adds a new maintenance schedule with server SERVER01 starting Jan. 1. 2017 18:30 and ending Jan 2. 2017 00:00

.EXAMPLE
    New-SCOMServerMaintenanceSchedule.ps1 -ServerName SERVER01 -start NOW -end 02/01/2017 -comment "your comment"

    Adds a new maintenance schedule with server SERVER01 starting NOW (adding 30 seconds by default) ending Jan 2. 2017

.EXAMPLE
    New-SCOMServerMaintenanceSchedule.ps1 -ServerName SERVER01 -start NOW -end 02/01/2017 -comment "your comment" -ManagementServer OPSMGR123.DOMAIN

    Adds a new maintenance schedule with server SERVER01 starting NOW (adding 30 seconds by default) ending Jan 2. 2017 connecting to specific management server

.NOTES
    Author: Martin Ehrnst /Intility AS
    Date: November 2016
    Version 0.9 Beta
    This version has a default of non reccuring schedule and has a hard coded reason for maintenance. You can change this by altering the script directly
    Use at own risk

#>

param(
[Parameter(Mandatory=$True)]
[string[]]$ServerName,
[Parameter(Mandatory=$True)]
[string]$ManagementServer = 'localhost',
[Parameter(Mandatory=$True)]
[string]$start,
[Parameter(Mandatory=$True)]
[string]$End,
[Parameter(Mandatory=$True)]
[string]$Comment)

#####FUNCTIONS#######
function Input-Date{
param(
[string]$dateTime)

Do
{    
$Inputdate = $dateTime
if ($Inputdate -eq "NOW"){
    $Inputdate = (Get-Date).AddSeconds(30)}
Else{
$Inputdate = $Inputdate -as [datetime]}

if (!$Inputdate) { "Not A valid date and time"
break}

} while ($Inputdate -isnot [datetime])

$Inputdate
}

Function Get-SCOMServers{
Param(
[STRING[]]$Name
)
#Getting servers from Windows and Linux Computer Class
foreach ($O in $Name){
$Server = Get-ScomClass -id 'e817d034-02e8-294c-3509-01ca25481689','d3344825-d5d1-2656-852e-1053269703c0' | Get-SCOMClassInstance | where {$_.DisplayName -like "$o.*"}
if(!$Server){
Write-Host "Could not find server. Please check input"
break}
else{
$server}
}
}

######END FUNCTIONS####

#Maintenance start time
$InputStart = Input-Date -dateTime $start -ErrorAction Stop

#Maintenance end time
$InputEnd = Input-Date -dateTime $End -ErrorAction Stop

#Checking if module is loaded. if not load and connect to MS
$Module = Get-Module -Name OperationsManager
if (!$Module){
Import-Module OperationsManager}

New-SCOMManagementGroupConnection -ComputerName $ManagementServer

$Object = (Get-SCOMServers -Name $ServerName).ID
[STRING]$SheduleName = $ServerName + ":" + "Created with Script"
$Duration = (New-TimeSpan -Start $InputStart -End $InputEnd).TotalMinutes
$Reason = 'PlannedApplicationMaintenance'
$Frequency = '1' #1 Equals no frequency or 'once'

try{
New-SCOMMaintenanceSchedule -Name $SheduleName -Enabled $true -MonitoringObjects $Object -ActiveStartTime $InputStart -ActiveEndDate $InputEnd -Duration $Duration -ReasonCode $Reason -FreqType 1 -Comments $Comment -ErrorAction Stop
}
catch{
write-host "Something went wrong"
$_.Exception.Message}

 

Share this:

  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on X (Opens in new window) X
  • Click to share on Reddit (Opens in new window) Reddit
MPAuthoring

OpsMgr & External Services PT2

  • 16/10/201607/01/2025
  • by Martin Ehrnst

Continuing the series where i try to season Operations Manager with data from external sources. Where In part one I created a CSV file containing the name and url to yr.no’s open XML API. I created two classes and one relationship and discoveries for these. You can find part one of OpsMgr and External services here

In part two, I will continue with the weather management pack focusing on the Health Model by adding rules and monitors to Our location Objects. Full MP and VSAE Project will be included at the end of this post.

The rules are perf. Collection rules which collects the forecasted and observed temperature from yr.no. The monitor is added to alert when observed temperature is below what is set as alert temperature on each location (Object). For the configurable alert temperature I have added a New property to the weather location class.

  <Property ID="LocationName" Key="true" Type="string" />
  <Property ID="LocationURL" Key="false" Type="string" />
  <Property ID="LocationAlertTemp" Key="false" Type="int" />

Which also means that Our discovery script has changed as well With the following line.

$instance.AddProperty("$MPElement[Name='TheWeatherSolution.WeatherLocation']/LocationAlertTemp$",$LocationAlertTemp)

Temperature (perf.) Collection rules

If you explore the API from yr, you will see that you get forecast for different periods. I noticed that when you Access the forecast XML node the first Object will always be for the period youre in right now which makes it easier to Write the script when we could just use the first Object.

An example of how the response:

from          : 2016-10-16T21:00:00
to            : 2016-10-17T00:00:00
period        : 3
#comment      : { Valid from 2016-10-16T21:00:00 to 2016-10-17T00:00:00 ,  Valid at 2016-10-16T21:00:00 }
symbol        : symbol
precipitation : precipitation
windDirection : windDirection
windSpeed     : windSpeed
temperature   : temperature
pressure      : pressure

As i mentioned in part one of this blog series I have gotten tips from Trond Hindenes for the MP it self and Kevin Holman for the VSAE fragments used in PowerShell  rules and monitors. For this MP I created two collection rules for temperatures. Both observed and forcasted temp. (don’t ask, i know this data is available at www.yr.no).

The rules use the similar PS script, and after adding the OpsMgr Magic around it this is how it ended up.

param([string]$LocationURL, [string]$LocationName)
                  
                  # Add the SCOM API and Propertybag for output
                  $api = New-Object -comObject "MOM.ScriptAPI"
                  $bag = $api.CreatePropertyBag()
                  $ScriptName = "GetTemperatureObservation.ps1"

                  # Logging
                  $api.LogScriptEvent($ScriptName,1234,0,"$ScriptName script is starting")
                  
                  [xml]$yr = Invoke-WebRequest -Uri $LocationURL
                  #Getting the latest observation
                  $Observation = $yr.SelectNodes("//observations").weatherstation | Select-Object -First 1
                  [int]$ObservationTemp = $Observation.temperature.value

                  #Adding the value from the script into the propertybag
                  $bag.AddValue("ObservationTemp",$ObservationTemp)
                  #Logging
                  $api.LogScriptEvent($ScriptName,1235,0,"$ScriptName script is complete")

                  #Outputting the bag
                  $bag
                  ]]>

As you see, the script takes location URL as a parameter which needs to be added to the fragment by Kevin if you use it.

                <Parameters>
                  <Parameter>
                    <Name>LocationURL</Name>
                    <Value>$Target/Property[Type="TheWeatherSolution.WeatherLocation"]/LocationURL$</Value>
                  </Parameter>
                </Parameters>

After a few days you hopefully have a graph like this With observed and forecasted temperature

Observed temp vs forecast

 

Monitor

I don’t like having unmonitored Objects in SCOM so we needed to add a monitor to these locations, dont know why i need to be alerted by SCOM when it’s cold out, but now i can. Again, based on Kevins fragment created a two state PowerShell monitor which grabs the LocationAlertTemp parameter from each location and compares it to the observed temperature by yr.no. Anything less than Our Alert Temp will change the state and rase an alert. As you can imagine, no drastic changes to the PowerShell script we used in the rule, but some changes to the SCOM bits. This scipt/monitor takes two parameters that need to be added. First the location URL and the LocationAlertTemp.

                  param([string]$LocationURL,[string]$LocationName,[int]$LocationAlertTemp)
                  # Load MomScript API and PropertyBag function
                  $api = new-object -comObject 'MOM.ScriptAPI'
                  $bag = $api.CreatePropertyBag()

                  #Log script event that we are starting task
                  $api.LogScriptEvent("TooCold.ps1",6789,0, "Starting toocold.ps1 script")

                  [xml]$yr = Invoke-WebRequest -Uri $LocationURL
                  #Getting the latest observation
                  $Observations = $yr.SelectNodes("//observations").weatherstation | select-object -First 1
                  [int]$Obstemperature = $Observations.temperature.value
                  $temperatureUnit = $Observations.temperature.unit
                  if ($Obstemperature -lt $LocationAlertTemp){
                  $bag.AddValue("Result","BadCondition")
                  #$bag.AddValue("Description", "It is freaking cold observed temperature" + "$obstemperature" + "$temperatureUnit")
                  }
                  else{
                  $bag.addvalue("Result","GoodCondition")
                  }
                  $bag

Below the script body I have added,

 <Parameters>
                  <Parameter>
                    <Name>LocationURL</Name>
                    <Value>$Target/Property[Type="TheWeatherSolution.WeatherLocation"]/LocationURL$</Value>
                  </Parameter>
                  <Parameter>
                    <Name>LocationAlertTemp</Name>
                    <Value>$Target/Property[Type="TheWeatherSolution.WeatherLocation"]/LocationAlertTemp$</Value>
                  </Parameter>
                </Parameters>

If everything is working correctly you should have all Your locations monitored, and depending on observed temperature and the alert temp parameter it’s either healthy or in warning state

locationmonitoredalerttemp

locationmonitoredalerttempwarningstate

I have made my MP and VSAE Project available for download here – please note that i do not take any responsibility for this MP and it’s not something i would sell or add to Our Production environment before i have made more testing and cleaned all displaynames, alert text etc. Key file are also excluded.

 

Share this:

  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on X (Opens in new window) X
  • Click to share on Reddit (Opens in new window) Reddit
Automation

Script to add SCOM agent management group

  • 03/10/201607/01/2025
  • by Martin Ehrnst

 

We wanted to change how SCOM agents is installed and configured. That involved some scripting. As a part of the process we add a management Group to the agent after it is installed. SCOM 2016 is also released now so if you want to migrate instead of upgrading, you can use this script to add an additional MG.

Script will have two mandatory parameters management server and management Group name. A Third parameter is optional, which is the port number and defaults to 5723. You can save the below script as Add-SCOMManagementGroup.ps1

<#

.SYNOPSIS
    Adding management group to agent

.DESCRIPTION
    Adding first or additional management group to agent. for example use this to multihome agent when migrating to a new management group.

.EXAMPLE
    Add-SCOMManagementGroup.ps1 -ManagementServer SCOM01.domain -MGMTGroupName SCOMMG

    Adds SCOMMG to the agent and set SCOM01 as primary management server. Default port 5723

.EXAMPLE
    Add-SCOMManagementGroup.ps1 -ManagementServer [Primary MS] -MGMTGroupName [Management group name] -port [INT]

    Adds SCOMMG to the agent and set SCOM01 as primary management server and set port you specify

.NOTES
    Author: Martin Ehrnst /Intility AS

#>

Param(
  [Parameter(Mandatory=$True)]
   [string]$ManagementServer,
	
   [Parameter(Mandatory=$True)]
   [string]$MGMTGroupName,

   [Parameter(Mandatory=$false)]
   [int]$Port = "5723"
)

$ErrorActionPreference='Stop'

Write-Warning "This will restart the agents health service"

#Adding MG to the agent
try{
$Agent = New-Object -ComObject AgentConfigManager.MgmtSvcCfg
$Agent.AddManagementGroup("$MGMTGroupName", "$ManagementServer", "$Port")}

catch{
CLS
Write-host "An error occured please se exeption message:"

Write-error $_.Exception.Message
BREAK
}

get-service HealthService | Restart-Service

Write-Host "Agent connected to the following management groups"
$Agent.GetManagementGroups()

 

 

Share this:

  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on X (Opens in new window) X
  • Click to share on Reddit (Opens in new window) Reddit

Posts pagination

1 … 6 7 8 9 10 … 13

Popular blog posts

  • Webinar: Multi-tenant resource management at scale with Azure Lighthouse
  • Azure Application registrations, Enterprise Apps, and managed identities
  • Azure Monitor Managed Prometheus
  • Azure token from a custom app registration
  • OpsMgr & External Services PT2

Categories

Automation Azure Azure Active Directory Azure Bicep Azure DevOps Azure Functions Azure Lighthouse Azure Logic Apps Azure Monitor Azure Policy Community Conferences CSP Monitoring DevOps GitHub Guest blogs Infrastructure As Code Kubernetes Microsoft CSP MPAuthoring OMS Operations Manager Podcast Powershell Uncategorised Windows Admin Center Windows Server

Follow Martin Ehrnst

  • X
  • LinkedIn

RSS feed RSS - Posts

RSS feed RSS - Comments

Microsoft Azure MVP

Martin Ehrnst Microsoft Azure MVP
Adatum.no use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it. Cookie Policy
Theme by Colorlib Powered by WordPress