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

I have moved script logging to OMS

  • 15/12/201607/01/2025
  • by Martin Ehrnst

For some time I have “rewritten” my scripts to utilize variables, connections  and other assets in Azure automation. While doing this I have moved all script logging to the cloud as well.

previously all scripts were logging to a file or to the computers event log. I have some experience with sending custom data to OMS. Using their API i have sent weather data and the technique could easily be transferred to do my script logging.

I thought about  creating a module for this for a while, but luckily, the great Mr Tao Yang already did it and it is available on GitHub, PSGallery and in Azure automation. The only thing i had to do was wrap everything in a function and call that each time i needed a log entry sent from my scripts.

Based on Tao’s OMSDataInjection module. Here’s how my function looks like

<#
    .DESCRIPTION
        Function sends a entry to OMS Log analytics.
        Used to send script log entries to OMS in a 'one liner'


    .NOTES
        Requires Tao Yang's OMSDatainjection Module: https://github.com/tyconsulting/OMSDataInjection-PSModule/releases/tag/1.1.1
        Author: Martin Ehrnst
        www.adatum.no
    
    .CHANGELOG
        06.12.16: Initial function release
    
#>

param (
    [parameter(Mandatory=$true)]
    [string]$Message,
    [parameter(Mandatory=$true)]
    [ValidateSet('Information','Warning','ERROR')]
    [string]$Severity
    )

$LogEntry = @{
  ScriptName = scriptName
  Severity = $Severity
  RanAT = $env:COMPUTERNAME
  Message  = "$Message"
  LogTime  = [Datetime]::UtcNow
}

$SendLog= New-OMSDataInjection -OMSWorkSpaceId '**************' -PrimaryKey '********************************' -LogType 'test' -UTCTimeStampField 'LogTime' -OMSDataObject $LogEntry
}

The only thing you have to before you use it is to define your script name, OMSWorkspaceID, PrimaryKey and a LogType. When all is good. Call this each time you want to send a log entry

Send-LogEntry -Message "testing 123" -Severity Warning

Here is a script, from on prem to Azure Automation to run on a Hybrid worker using this function to do the logging.

Please note that since i run through azure automation i have created a connection object and reffeer to that using instead of specifying the ID and Key.

<#
    .NAME
        Close-OldSCOMAlerts.ps1


    .DESCRIPTION
        Closes SCOM alerts based on severity, resolution state, repeat count etc. Alter settings in the configuration regions.
        The script requires OpsMgr module and Azure automation. I Reccomend storing the credentials and variables as assets and run the script on a hybrid worker.
        If you want to run locally, change the script parameters and hard code the values.


    .NOTES
        Requires Operations Manager Module and Tao Yang's OMSDatainjection Module
        Author: Martin Ehrnst
        Version: 1.1 Initial (Azure automation) Release 28.11.16
        www.adatum.no
        www.intility.no
    
    .CHANGELOG
        08.12.16: Using Tao Yang's OMSDataInjectionModule to ship script logs to OMS
        Removed local logging
    
#>

#region Configuration
$ErrorActionPreference = "Continue"
#$VerbosePreference = "Continue" #Uncomment to see verbose output
[int]$RepeatCount = 2 #Alerts with less than x repeat count will close
[int]$AlertAgeHours = 3 #Alert Age (older gets closed)
[string]$AlertSeverity = "Information" #specify alert severity you want to close
[int]$ResolutionState = 0 #0 NEW
[int]$SetState = 255 #255 CLOSED
[string]$Comment = "Alert closed by script in azure automation" #Comment to set on the closed alerts
#endregion

#region Modules
Import-Module "C:\Program Files\WindowsPowerShell\Modules\OMSDataInjection\1.1.1\OMSDataInjection.psm1"

$module = Get-Module -Name OperationsManager
if (!$module){
    Write-Verbose "Could not find SCOM Module. Importing"
    Import-Module OperationsManager -Cmdlet Get-SCOMalert, New-SCOMManagementGroupConnection, Update-SCOMAlert, Set-SCOMAlert
    }
#endregion

#region OMSLogging
    $OMSWorkspace = Get-AutomationConnection 'I2-Intility-Test'
    
    
function Send-LogEntry{
<#
    .DESCRIPTION
        Function sends a entry to OMS Log analytics.
        Used to send script log entries to OMS in a 'one liner'


    .NOTES
        Requires Tao Yang's OMSDatainjection Module: https://github.com/tyconsulting/OMSDataInjection-PSModule/releases/tag/1.1.1
        Author: Martin Ehrnst
        www.adatum.no
        www.intility.no
    
    .CHANGELOG
        06.12.16: Initial function release
    
#>
param (
    [parameter(Mandatory=$true)]
    [string]$Message,
    [parameter(Mandatory=$true)]
    [ValidateSet('Information','Warning','ERROR')]
    [string]$Severity
    )

$LogEntry = @{
  ScriptName = 'Close-OldSCOMAlerts.ps1'
  Severity = $Severity
  RanAT = $env:COMPUTERNAME
  Message  = $Message
  LogTime  = [Datetime]::UtcNow
}

$SendLog= New-OMSDataInjection -OMSConnection $OMSWorkspace -LogType 'AutomationLogs' -UTCTimeStampField 'LogTime' -OMSDataObject $LogEntry

}
#endregion

Send-LogEntry -Message "Starting azure automation runbook to close old scom alerts" -Severity Information

#region AzureConfig
    
    $SCOMOperator = Get-AutomationPSCredential -Name 'AzureAutomationSCOMOperator'
    $SCOMManagementServer = Get-AutomationVariable -Name 'SCOMProdSDKServer'

#endregion

Try {
    #Connecting to SCOM management server
    Write-Verbose "Connecting to $ManagementServer"
    New-SCOMManagementGroupConnection -ComputerName $SCOMManagementServer -Credential $SCOMOperator
    }
Catch {
    Write-Error "$_.Exception.Message"

    Send-LogEntry -Message "$_.Exception.Message" -Severity ERROR
    }

#Actual alert work
$Date = (Get-Date).AddHours(-$AlertAgeHours).ToUniversalTime() #Setting Alert age and converting to UTC

$Alerts = Get-ScomAlert | where {$_.TimeRaised -lt $Date `
    -and $_.ResolutionState -eq $ResolutionState `
    -and $_.Severity -match $AlertSeverity `
    -and $_.RepeatCount -lt $RepeatCount `
    -and $_.IsMonitorAlert -eq $false
    }
if ($Alerts){
        $count = $alerts.Count
        Send-LogEntry -Message "Closing $count alerts" -Severity Information
       
        $alerts | Set-SCOMAlert -ResolutionState $SetState -Comment $Comment
        Send-LogEntry -Message "Finished - closed $count alerts" -Severity Information
        Write-Output "closed $count alerts"
    }
else{
    Write-Output "No old alerts to close. Exiting script"
    Send-LogEntry -Message "Finished. No alerts to close" -Severity Information
    }

 

Share this:

  • Share on LinkedIn (Opens in new window) LinkedIn
  • Share on X (Opens in new window) X
  • Share on Reddit (Opens in new window) Reddit
OMS

SCOM and OMS: The agents

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

Both SCOM and OMS are in most ways dependent on agents installed on each server being monitored. If you have SCOM today you probably run Microsoft Operations Manager Agent (MOM) which is shipped with SCOM 2012 media and installed through the SCOM console or a SW deployment tool ConfigMgr etc.

OMS on the other hand uses the new Microsoft Monitoring Agent (MMA) which is available for download within your OMS workspace or through MSFT download center. MMA is said to be the mother of all agents which should be used by every Microsoft software that require an agent.

NB: At some point (SCOM 2012 SP1?) the agent actually got rebranded to Microsoft Monitoring Agent. It is stil not the same you get from OMS

 

The reason for looking in to the agents is that we one situation wher we lost contact with one server belonging to a customer (a customer of my employee Intility).

It turned out that they had signed up for OMS and configured the MMA agent to. At some point this deleted our SCOM configuration and we lost monitoring on that server.

As OMS is fast forwarding these days we will have to be proactive and support agent/servers directly reporting to other OMS workspaces than the one connected to our SCOM environment.

 

After some testing here is what i found is the main differences on these agents:

Supports MOM/SCOM Agent

OMS Agent (MMA)

SCOM Workgroup X X
Multihome SCOM Workgroup X X*
OMS Reporting X (through SCOM) X
Multihome OMS Workspace X*
Hybrid Worker support X

*I do not know if there is a limitation on how many connections an agent can have, but I have tried 5 in total. 3 OMS workspaces and 2 SCOM work groups.

 

Screenshots showing MMA

Microsoft Monitoring Agent Properties Operations Manager Azure Log Analytics (OMS) Proxy Setüngs Properbes An agent can report to mulbple management groups. If you use Operations Manager integration with Active Directory Domain Services (AD DS), the list of management groups can be updated automabcally. Automabcally update management group assignments from AD DS If you select this opton, the agent will query AD DS for the list of management groups to which it has been assigned. If any are found, they are added to the ist. Managementgroups thathave been found in AD DS cannot be removed by using this property sheet. Managemen t Groups: Primar y Management Ser.. Port •e Assignmen t Agent Action

 

MOM rebranded

Microsoft Monitoring Agent Properties Operations Manager Properties An agent can report to multipla management groupe f you use Operations Manager integration with Active Directory Domain Services (AD DS). the list of management groups can be updated automatically r Automatically update management group assignments from AD DS f you select this option. the agent will query AD DS for the list of management groups to which t has been assigned f any are found. they are added to the list Management groups that have been found in AD DS cannot be removed by using this property sheet Management Groups: Prim Man Ser Port

 

At this point we plan to upgrade all agents making sure customers are able to report to their own OMS workspace without interfering with our central SCOM and OMS installations.

SCOM 2016 is also shipped with the MMA agent and is likely the same but with a different version.

 

Let me know if you have something to add and I will update my post accordingly.

 

 

Bombshell:

If you extract the .MSI from MMASetup******.exe you end up with a MSI which installs the “old” MOM agent

Share this:

  • Share on LinkedIn (Opens in new window) LinkedIn
  • Share on X (Opens in new window) X
  • Share on Reddit (Opens in new window) Reddit
MPAuthoring

SCOM Task to restart Agent – am i complicating…

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

As part of planning to migrate a large (3000 + VM) SCOM 2012 R2 environment to 2016 we will need to do a bit of agent configuration. I have created two tasks in Our SCOM console to help us add or delete management Groups from the monitored computers (when moving all agents we probably will use some other orchestration). The problem is that you will have to restart the agents HealthService to save new configuration. Since we execute the task/script through the Health service the task will fail when we attempt to restart. You may experience Your task to work, as in you will have the managment Group added, but you will not see any output.
Over the years People have published a lot of scripts that restarts the agents but unfortunately I have not managed to get them to work properly.

Therfore, i am complicating Things…

I created a script which creates a scheduled task set to run in one minute before it expires and deletes. The Whole thing Works perfectly, but there has to be another way?

<#
NAME: Create-SCOMAgentRestartSchedTask.ps1

.DESCRIPTION
    Creates a scheduled task on the computer which will restart scom health service.
    Script is used as agent task within SCOM as a 'hack' to restart agent through the console.
    
.NOTES
    Martin Ehrnst /Intility AS
    www.adatum.no

    Intial release November 16
    Version 1.0


#>

#Do some logging to the Operations Manager Event Log
$api = new-object -comObject MOM.ScriptAPI
$api.LogScriptEvent("Create-SCOMAgentRestartSchedTask.ps1", 1001, 4, "Creating a scheduled task to restart SCOM health service. Task will expire and delete after it's finished.")

$Service = "HealthService"
$Action = New-ScheduledTaskAction -Execute "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -Argument "Get-Service $Service | restart-service -force"
$run = (Get-Date).AddMinutes(1) # Two minutes from now
$User = 'SYSTEM'
$trigger = New-ScheduledTaskTrigger -Once -At ($run)
$settings = New-ScheduledTaskSettingsSet -DeleteExpiredTaskAfter 00:00:01
Register-ScheduledTask -TaskName "Restart SCOM HealthService" -User $user -InputObject (
  (
    New-ScheduledTask -Action $Action -Trigger $trigger -Settings $settings
) | %{ $_.Triggers[0].EndBoundary = $run.AddMinutes(5).ToString('s') ; $_ })
write-host "created a task to restart $service in one minute"

I know that Microsoft have a recovery action to restart the agent when it is using too much memory and similar, but I haven’t broken Down their code.

taskinfosystemeventlog

Share this:

  • Share on LinkedIn (Opens in new window) LinkedIn
  • Share on X (Opens in new window) X
  • Share on Reddit (Opens in new window) Reddit

Posts pagination

1 … 6 7 8 9 10 … 15

Popular blog posts

  • Azure Application registrations, Enterprise Apps, and managed identities
  • Azure token from a custom app registration
  • Azure managed Prometheus for existing AKS clusters
  • Windows Admin Center with SquaredUp/SCOM
  • Azure AD authentication in Azure Functions

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