14 Kasım 2015 Cumartesi

SCOM 2012 R2 Test Event MP

MP and scripts to test that SCOM internal monitoring is working.
Zip file contains:
—Management Pack
—VBS Event Script
—Scheduled Task
DOWNLOAD Link: SCOM.Test.MP

Ref: ScomGod

PowerShell Script to Update Alert Resolution

I use this to regenerate reminder alerts for certain alerts. This script will trigger for alerts with “Disk” in the name.
$MS = “yourRMS.yourCO.com”
$connect = New-SCOMManagementGroupConnection –ComputerName $MS
Get-SCOMAlert -criteria ‘ResolutionState = “0” AND Severity = “2”‘ |
Where-Object {$_.Name -like “*disk*” -and $_.IsMonitorAlert -eq $true} |
Set-SCOMAlert -ResolutionState 0 |
out-null

VBS Script to get AD Group Members

‘Script begins here
Dim objGroup, objUser, objFSO, objFile, strDomain, strGroup, Domain, Group
‘Change DomainName to the name of the domain the group is in
strDomain = Inputbox (“Enter the Domain name”, “Data needed”, “Default domain name”)
‘Change GroupName to the name of the group whose members you want to export
strGroup = InputBox (“Enter the Group name”, “Data needed”, “Default group name”)
Set objFSO = CreateObject(“Scripting.FileSystemObject”)
‘On the next line change the name and path of the file that export data will be written to.
Set objFile = objFSO.CreateTextFile(“C:\” & strGroup & ” – Members.txt”)
Set objGroup = GetObject(“WinNT://” & strDomain & “/” & strGroup & “,group”)
For Each objUser In objGroup.Members
objFile.WriteLine objUser.Name & ” – ” & objUser.Class
Next
objFile.Close
Set objFile = Nothing
Set objFSO = Nothing
Set objUser = Nothing
Set objGroup = Nothing
Wscript.Echo “Done”
Wscript.Echo “Please check the c: for your output file”

SCOM 2012 R2 Close All Alerts Script

This script will close all alerts in the console.
$RMSrv = “RMSSERVERNAME”
Add-PSSnapin “Microsoft.EnterpriseManagement.OperationsManager.Client”
Set-Location “OperationsManagerMonitoring::”
New-ManagementGroupConnection -ConnectionString:$RMSrv
Set-Location $RMSrv
$alerts = get-alert |where-object {$_.ResolutionState -eq 0}
foreach($alert in $alerts)
{
resolve-alert -comment “Resolving Alert” -Alert $alert
}

SCOM 2012 Put URL into Maintenance Mode

$Time = ((Get-Date).AddMinutes(30))
$Instance = Get-SCOMClassInstance -DisplayName “http://www.microsoft.com”
Start-SCOMMaintenanceMode -Instance $Instance -EndTime $Time -Reason “PlannedApplicationMaintenance” -Comment “Swift App Maintenance”

SCOM 2012 Batch File to Clear Health Service Cache

net stop HealthService
cd\
cd C:\Program Files\System Center 2012\Operations Manager\Server\Health Service State\Health Service Store
del *.* /F /Q
net start HealthService

Monitor an agent - but run response on a Management Server

This is a concept that I have seen several examples of, but realize not everyone knows of this capability.
You can create a rule, that targets a class hosted by an agent (such as Windows Server Operating System), but have a script response run on the Management Server to take action.
Here is a simple example:
      <Rule ID="Custom.Example.ResponseOnMS.Rule1" Enabled="true" Target="Windows!Microsoft.Windows.Server.OperatingSystem" ConfirmDelivery="false" Remotable="true" Priority="Normal" DiscardLevel="100">
        <Category>Maintenance</Category>
        <DataSources>
          <DataSource ID="DS" TypeID="Windows!Microsoft.Windows.EventProvider">
            <ComputerName>$Target/Host/Property[Type="Windows!Microsoft.Windows.Computer"]/NetworkName$</ComputerName>
            <LogName>Application</LogName>
            <Expression>
              <And>
                <Expression>
                  <SimpleExpression>
                    <ValueExpression>
                      <XPathQuery Type="UnsignedInteger">EventDisplayNumber</XPathQuery>
                    </ValueExpression>
                    <Operator>Equal</Operator>
                    <ValueExpression>
                      <Value Type="UnsignedInteger">100</Value>
                    </ValueExpression>
                  </SimpleExpression>
                </Expression>
                <Expression>
                  <SimpleExpression>
                    <ValueExpression>
                     <XPathQuery Type="String">PublisherName</XPathQuery>
                    </ValueExpression>
                    <Operator>Equal</Operator>
                    <ValueExpression>
                      <Value Type="String">MM</Value>
                    </ValueExpression>
                  </SimpleExpression>
                </Expression>
              </And>
            </Expression>
          </DataSource>
        </DataSources>
        <WriteActions>
          <WriteAction ID="PSWA" TypeID="Windows!Microsoft.Windows.PowerShellWriteAction" Target="SC!Microsoft.SystemCenter.ManagementServer">
            <ScriptName>ScriptOnMS.ps1</ScriptName>
            <ScriptBody>
# Add the SCOM API and Log event
$api = New-Object -comObject "MOM.ScriptAPI"
$api.LogScriptEvent("ScriptOnMS.ps1",2222,0,"This event is created by a script running on the MS")
            </ScriptBody>
            <TimeoutSeconds>30</TimeoutSeconds>
          </WriteAction>
        </WriteActions>
      </Rule>
    </Rules>


This rule uses a simple event datasource looking for event 100, and source of “MM”. 
Then – it responds with a Write Action – but the Write Action has a Target of Management server.  This is the key part:
Target="SC!Microsoft.SystemCenter.ManagementServer">
My example is very simple – and runs PowerShell on the Management server, creating a single simple event in the OpsMgr log.

This design works in SCOM 2012 – where the response will execute on the Management Server that the agent is assigned to.
You can use this example to do things, like query the OpsDB and generate a specific alert in response to an agent side issue – or you can put the agent into Maintenance mode by passing the computername as a parameter to the script write action.
I will attach my MP example below.
Custom.Example.ResponseOnMS.xml.zip
Ref: Kevin Holman

Event Log rule to look for multiple reboots – a script WriteAction example

I had a customer looking for an example of how SCOM can monitor a server for multiple reboots in a period of time.
I previously wrote about the typical scenario of looking for repeated events in a defined time period here: http://blogs.technet.com/b/kevinholman/archive/2014/12/18/creating-a-repeated-event-detection-rule.aspx
However – this wont work across reboots.  The consolidator Condition Detection that keeps a count of multiple events across time is handled in memory, on the agent.  If the agent service or server is restarted – we lose the count because the workflow must reinitialize.
One way to handle this is via a script write action.  Essentially – a reboot is typically detected via a 6009 event in the SYSTEM log.  (Dirty shutdowns can be detected via 6008 event and you should already be monitoring for these)   However – in this example we don’t want an alert on every normal reboot.  We only want to know if a server is rebooted multiple times in a specific time period.
We can accomplish this via two rules.
One rule will use an Event datasource, but instead of alerting – we will execute a script WriteAction as the response to the event.  The script is a simple VBscript that looks in the system log for a specific duration of time, and counts the number of matching events.
Here is the rule:
      <Rule ID="Custom.Example.EventLogCheck.Event6009.Rule" Enabled="true" Target="Windows!Microsoft.Windows.Server.OperatingSystem" ConfirmDelivery="true" Remotable="true" Priority="Normal" DiscardLevel="100">
        <Category>Custom</Category>
        <DataSources>
          <DataSource ID="DS" TypeID="Windows!Microsoft.Windows.EventProvider">
            <ComputerName>$Target/Host/Property[Type="Windows!Microsoft.Windows.Computer"]/NetworkName$</ComputerName>
            <LogName>System</LogName>
            <Expression>
              <SimpleExpression>
                <ValueExpression>
                  <XPathQuery Type="UnsignedInteger">EventDisplayNumber</XPathQuery>
                </ValueExpression>
                <Operator>Equal</Operator>
                <ValueExpression>
                  <Value Type="UnsignedInteger">6009</Value>
                </ValueExpression>
              </SimpleExpression>
            </Expression>
          </DataSource>
        </DataSources>
        <WriteActions>
          <WriteAction ID="ScriptWriteAction" TypeID="Custom.Example.EventLogCheck.WA" />
        </WriteActions>
      </Rule>

The script is very simple:  You can reuse this just change the event ID, count, and time you want at the top.  You might also need to customize the events created by LogScriptEvent to suit your needs and provide a good message for the alert.
My log for a detection of 3 events looks like:
Call oAPI.LogScriptEvent("CheckEventLog.vbs",1001,1,": CRITICAL : Event " & EventId & " has been detected " & Count & " or more times in the past " & Minutes & " minutes")
This will log a critical event with ID 1001 in the OpsMgr event log on the agent, with the event description resembling this:
image

Here is the script:

'==========================================================================
'
' NAME: CheckEventLog.vbs
'
' COMMENT: This is a write action script to inspect the event log for previous events
'
' Change the values for EventId, Count, and Minutes for your write action example  (minutes is expressed as a negative number offset)
'
'==========================================================================
Option Explicit
SetLocale("en-us")

Dim EventId, Count, Minutes
EventId = 6009
Count = 3
Minutes = -20

Dim oAPI
Set oAPI = CreateObject("MOM.ScriptAPI")

Dim strComputer
'The script will always be run on the machine that generated the original event
strComputer = "."

Dim strTime 
strTime = Time

    'Check to see if this event has been logged x occurrences in n minutes
    Dim dtmStartDate, iCount, colEvents, objWMIService, objEvent
    Const CONVERT_TO_LOCAL_TIME = True
     Set dtmStartDate = CreateObject("WbemScripting.SWbemDateTime")
     dtmStartDate.SetVarDate dateadd("n", Minutes, now)' CONVERT_TO_LOCAL_TIME
     
     iCount = 0
     Set objWMIService = GetObject("winmgmts:" _
         & "{impersonationLevel=impersonate,(Security)}!\\" _
         & strComputer & "\root\cimv2")
     Set colEvents = objWMIService.ExecQuery _
         ("Select * from Win32_NTLogEvent Where Logfile = 'SYSTEM' and " _
            & "TimeWritten > '" & dtmStartDate & "' and EventCode = " & EventId & "") 
     For Each objEvent In colEvents
        iCount = iCount+1  
     Next
    If iCount => Count Then
        Call oAPI.LogScriptEvent("CheckEventLog.vbs",1001,1,": CRITICAL : Event " & EventId & " has been detected " & Count & " or more times in the past " & Minutes & " minutes") 
        WScript.Quit
    End If
        Call oAPI.LogScriptEvent("CheckEventLog.vbs",1002,0,": INFO : Event " & EventId & " was detected, but has not been detected " & Count & " or more times in the past " & Minutes & " minutes")
    Wscript.Quit

We just need to wrap this up into a write action:



      <WriteActionModuleType ID="Custom.Example.EventLogCheck.WA" Accessibility="Public" Batching="false">
        <Configuration />
        <ModuleImplementation Isolation="Any">
          <Composite>
            <MemberModules>
              <WriteAction ID="ScriptWrite" TypeID="Windows!Microsoft.Windows.ScriptWriteAction">
                <ScriptName>CheckEventLog.vbs</ScriptName>
                <Arguments />
                <ScriptBody><![CDATA[
'==========================================================================
'
' NAME: CheckEventLog.vbs
'
' COMMENT: This is a write action script to inspect the event log for previous events
'
' Change the values for EventId, Count, and Minutes for your write action example  (minutes is expressed as a negative number offset)
'
'==========================================================================
Option Explicit
SetLocale("en-us")

Dim EventId, Count, Minutes
EventId = 6009
Count = 3
Minutes = -20

Dim oAPI
Set oAPI = CreateObject("MOM.ScriptAPI")

Dim strComputer
'The script will always be run on the machine that generated the original event
strComputer = "."

Dim strTime 
strTime = Time

    'Check to see if this event has been logged x occurrences in n minutes
    Dim dtmStartDate, iCount, colEvents, objWMIService, objEvent
    Const CONVERT_TO_LOCAL_TIME = True
     Set dtmStartDate = CreateObject("WbemScripting.SWbemDateTime")
     dtmStartDate.SetVarDate dateadd("n", Minutes, now)' CONVERT_TO_LOCAL_TIME
     
     iCount = 0
     Set objWMIService = GetObject("winmgmts:" _
         & "{impersonationLevel=impersonate,(Security)}!\\" _
         & strComputer & "\root\cimv2")
     Set colEvents = objWMIService.ExecQuery _
         ("Select * from Win32_NTLogEvent Where Logfile = 'SYSTEM' and " _
            & "TimeWritten > '" & dtmStartDate & "' and EventCode = " & EventId & "") 
     For Each objEvent In colEvents
        iCount = iCount+1  
     Next
    If iCount => Count Then
        Call oAPI.LogScriptEvent("CheckEventLog.vbs",1001,1,": CRITICAL : Event " & EventId & " has been detected " & Count & " or more times in the past " & Minutes & " minutes") 
        WScript.Quit
    End If
        Call oAPI.LogScriptEvent("CheckEventLog.vbs",1002,0,": INFO : Event " & EventId & " was detected, but has not been detected " & Count & " or more times in the past " & Minutes & " minutes")
    Wscript.Quit
]]></ScriptBody>
                <TimeoutSeconds>60</TimeoutSeconds>
              </WriteAction>
            </MemberModules>
            <Composition>
              <Node ID="ScriptWrite" />
            </Composition>
          </Composite>
        </ModuleImplementation>
        <InputType>System!System.BaseData</InputType>
      </WriteActionModuleType>

Lastly – we create a simple Alert Generating rule – to look in the Operations Manager event log – to alert on the “1001” event ID with source “Health Service Script” and EventDescription contains “CRITICAL”

      <Rule ID="Custom.Example.EventLogCheck.MultipleReboots.Rule" Enabled="true" Target="Windows!Microsoft.Windows.Server.OperatingSystem" ConfirmDelivery="true" Remotable="true" Priority="Normal" DiscardLevel="100">
        <Category>Alert</Category>
        <DataSources>
          <DataSource ID="DS" TypeID="Windows!Microsoft.Windows.EventProvider">
            <ComputerName>$Target/Host/Property[Type="Windows!Microsoft.Windows.Computer"]/NetworkName$</ComputerName>
            <LogName>Operations Manager</LogName>
            <Expression>
              <And>
                <Expression>
                  <SimpleExpression>
                    <ValueExpression>
                      <XPathQuery Type="UnsignedInteger">EventDisplayNumber</XPathQuery>
                    </ValueExpression>
                    <Operator>Equal</Operator>
                    <ValueExpression>
                      <Value Type="UnsignedInteger">1001</Value>
                    </ValueExpression>
                  </SimpleExpression>
                </Expression>
                <Expression>
                  <SimpleExpression>
                    <ValueExpression>
                      <XPathQuery Type="String">PublisherName</XPathQuery>
                    </ValueExpression>
                    <Operator>Equal</Operator>
                    <ValueExpression>
                      <Value Type="String">Health Service Script</Value>
                    </ValueExpression>
                  </SimpleExpression>
                </Expression>
                <Expression>
                  <RegExExpression>
                    <ValueExpression>
                      <XPathQuery Type="String">EventDescription</XPathQuery>
                    </ValueExpression>
                    <Operator>ContainsSubstring</Operator>
                    <Pattern>CRITICAL</Pattern>
                  </RegExExpression>
                </Expression>
              </And>
            </Expression>
          </DataSource>
        </DataSources>
        <WriteActions>
          <WriteAction ID="Alert" TypeID="Health!System.Health.GenerateAlert">
            <Priority>1</Priority>
            <Severity>1</Severity>
            <AlertName />
            <AlertDescription />
            <AlertOwner />
            <AlertMessageId>$MPElement[Name="Custom.Example.EventLogCheck.MultipleReboots.Rule.AlertMessage"]$</AlertMessageId>
            <AlertParameters>
              <AlertParameter1>$Data/EventDescription$</AlertParameter1>
            </AlertParameters>
            <Suppression />
            <Custom1 />
            <Custom2 />
            <Custom3 />
            <Custom4 />
            <Custom5 />
            <Custom6 />
            <Custom7 />
            <Custom8 />
            <Custom9 />
            <Custom10 />
          </WriteAction>
        </WriteActions>
      </Rule>
After 3 reboots in 20 minutes – we get this:”"
image

I will attach my example management pack below:
Custom.Example.EventLogCheck.xml.zip

Ref: Kevin Holman

UR7 for SCOM 2012 R2

KB Article for OpsMgr:  https://support.microsoft.com/kb/3064919
KB Article for all System Center components:  https://support.microsoft.com/en-us/kb/3069110