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
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
Automation

Using webhook in scom subscription (POC)

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

Recently, I was at System Center Universe (Now, Experts Live) in Berlin. During one side session i got talk to Cameron Fuller (Microsoft MVP) and I asked if he knew if anybody had used azure automation and it’s webhook capabilites in a SCOM subscription.

At Intility (my employer) we have developed an alert central which handles alerts from Solarwinds and other systems we use daily. OpsMgr is one of few systems that still tap directly in to our ticketing system, but were working on a change here. Webhooks and azure automation is one thing were looking at.

My attempt (if possible), using webhooks and Azure automation is to be able to send alerts from SCOM, and not have something query for new alerts when there nothing to handle. Cameron quickly reached out to his fellow MVPs and a few ours later i got a reply. Turns out that Jakob Gottlieb Svendsen (MVP) from Coretech had used webhooks in a recovery task. He basicly done all the work now :).

http://blog.coretech.dk/jgs/azure-automation-scom-triggering-a-runbook-as-a-recovery-task-using-webhooks/ (read this :))

The rest of this post will quickly show how to.

 

  • Create azure automation account
  • Create a new runbook
  • Add webhook
  • Runbook parameter
  • SCOM Command Channel and subscription

 

Azure Automation Account

 

Search for automation accounts in services and add a new Automation account. Use an existing resource group or create a new. After wizard is finished we should have an account assigned to a subscription.

automationaccount

 

By now you have probably read Jakobs blog and you have a new runbook in place, but i will guide you through anyway 🙂

Create a new runbook and use “Powershell workflow”. Once finished you will be sent to the online editor which is fine for now, but i suggest you download azure automation addon for ISE if you plan to do a lot of scripting here 🙂

Azure Automation PS worflow will start like this. If you add script parameter and publish where able to create a webhook. Place your normal PS script between the two curly brackets.

workflow 'your runbook name'

{

Param [object]($WebhookData)

}

I have adde the parameter already, that way we are able to create webhook an parameter at the next step.

Next task is to create a webhook for your runbook. With a webhook you are able to call the runbook with a URL and also pass parameters with JSON data inside the url. (Heres where the parameter for your webhook and script comes in)

Remember, copy your webhook URL – it’s not available after it is created

webhook1

 

After youre ‘hooked’ add paramters and define where to run. For this test i just fire it off in azure, but you can run your script on prem with the hybrid worker. Use your script parameter in the webhook data input.

webhook

You have probably added your own script inside the Azure workflow already, but here is my OpsMgrAlertHandlerTEST script which is based on Jakobs example and will output some key alert datato the console. Instead of just output it to the console i can now pass this information to our alert central by triggering a new runbook or adding it directly within this script.

 

workflow OpsMgrAlertHandlerTEST

{

param (

[object]$WebhookData

)



    $WebhookName    =   $WebhookData.WebhookName

    $WebhookHeaders =   $WebhookData.RequestHeader

    $WebhookBody    =   $WebhookData.RequestBody



    $Inputs = ConvertFrom-JSON $webhookdata.RequestBody

    $ComputerName = $Inputs.ComputerName

$AlertName = $Inputs.Alert

$ResolutionState = $Inputs.State

$AlertID = $Inputs.AlertID



    Write-Output "Computername: $ComputerName"

Write-Output "Alert: $AlertName"

Write-Output "State: $ResolutionState"

Write-Output "ID: $AlertID"

Write-Output "$Inputs"

}

 

From scom we will use powershell to POST alert data with invoke-restmethod and the URL you copied from the webhook configuration, right?

Again Jakob is apparently our JSON webhook guy http://blog.coretech.dk/jgs/azure-automation-using-webhooks-part-1-input-data/

SCOM Command Channel and subscription

 

Our final step is to create a command channel, subscriber and a subscription to trigger the runbook. From the admin panel in scom create a new command notification channel

channel1

In settings we will add path to Powershell and a command to run. Remember. Webhook url and the parameters to POST

channel2

Here is my full commandline (i have removed my webhook uri here)

-executionpolicy Unrestricted -Command " &{Invoke-RestMethod -Method Post -Uri 'YOUR WEBHOOK URL' -Body (ConvertTo-Json -InputObject @{'ComputerName'='$Data[Default='Not Present']/Context/DataItem/ManagedEntityPath$\$Data[Default='Not Present']/Context/DataItem/ManagedEntityDisplayName$';'Alert'='$Data[Default='Not Present']/Context/DataItem/AlertName$';'State'='$Data[Default='Not Present']/Context/DataItem/ResolutionStateName$';'AlertID'='$Data/Context/DataItem/AlertId$'}) -ErrorAction Stop}"

Inside the JSON string we will pass Computer Name, Alert name and the resolution state. Modify this by using the picker on the right side. After you have created the channel, create a new subscriber to use with this channel and finally create the actual subscription

For this test/POC i have chosen to send all information alerts to this subscription. These are mostly rules i can close (and generate) during testing.

Subscriber and channel are the two we just created.

subscription

 

At this point you should have:

  • Azure automation account
  • Automation runbook, my example or your own
  • Web hook enabled
  • Command channel
  • Subscriber and subscription

 

Finally, lets test our solution. I have added all informational messages to this subscription. I will close one of those and cross my fingers. We can follow the process in azure portal

closealert


As you see the job is queued and in the output console we see the output from our webhook data
automationoutputwait

 

It worked!

automationoutput

 

 

As this is totally in  a proof of concept state for us i would greatly apriciate inputs on how we can accomplish the task using other methods.

As we see, using webhooks in a subscription works quite well. But i havent implemented it in our production environment or sent it to our alert central yet. I see some issues, one being limited by how many powershell scripts we can run at once. Jakob suggested maybe we will look in to creating a connector and let us query a subscription for new alerts but i haven’t gotten around to try it out.

 

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 … 3 4 5 6 7

Popular blog posts

  • SCOM Alerts to Microsoft Teams and Mattermost
  • How to move Azure blobs up the path
  • Creating Azure AD Application using Powershell
  • SCOM and OMS: The agents
  • Azure Application registrations, Enterprise Apps, and managed identities

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