Pavleck.Net

Monitoring, Scripting, and other Technologies

Archive for the 'SCOM' Category


Building dynamic groups using WMI Queries

Posted by Jeremy D. Pavleck on 12th August 2008

Occasionally I’ll get some interesting requests from clients. One of those requests happened recently.

My client wanted to be able to see all of the servers that a certain process was running on. It was a ‘roaming’ process, and could be on any number of servers at any given time.  That’s easily solved with a dynamic group, a WMI query, and a custom attribute. In this example, I’ll be using the ubiqutous Notepad.exe

  1. First, start the console, open the Authoring pane, then right click on attributes and select “Create New Attribute“.
  2. Give your attribute a name - I used “Notepad Running” - and a nice description, then hit next.
    SCOM - Create Attribute Wizard - General Properties Page

    SCOM - Create Attribute Wizard - General Properties Page

  3. Under “Discovery Type” select WMI Query and select your target and management pack. Windows Server_Extended is a good choice for something as open ended as our particular request is, but you can narrow it down if you’d like.
    Then hit next.

    SCOM - Create Attribute Wizard - Discovery Method

    SCOM - Create Attribute Wizard - Discovery Method

  4. Under WMI Configuration we will build our query. Enter root\cimv2 for the namespace and for the query we’ll be using “Select * FROM WIN32_Process where Name = “notepad.exe”. The Property Name field is the most important part, and one not a lot of people understand right away. The “Property Name” field is what SCOM pays attention to, and what you use when you build groups and rules. In this example, I only want processes with notepad.exe to be returned, so I specify that in my query. For the Property name, I’m using Handle, which will always return something, but I could have used almost anything - such as ProcessID.

    SCOM - Create Attribute Wizard - WMI Configuration

    SCOM - Create Attribute Wizard - WMI Configuration

    If I wanted to create a more generic attribute, I could have used the query “Select * FROM WIN32_Process”, with a property name of “Name”. Then I could create groups with attributes of <Attribute> equals <Process Name>. If you’d like to learn more about the various fields available to you, open CIM Studio, part of the WMI Administrative Tools bundle. When you execute a query, the column names are what we’re talking about here.

    CIM Studio - Results of WMI Query

    CIM Studio - Results of WMI Query

  5. After you’re done, hit finish and we’ll be back at the attributes pane. Do a quick search to make sure it was added, and we’re done here.

    SCOM - Search Results for custom attribute

    SCOM - Search Results for custom attribute

  6. Now right-click on groups and select “Create a new group”
    Give it a nice friendly name & description and for the management pack choose the same one you used when creating your attribute! That’s important, as dynamic inclusion rules only scope to what is available in the current management pack (And any dependent ones), so you’d be going crazy wondering where your attribute is if you used a different one. Then hit Next>

    SCOM - Create Attribute - Create Group Wizard

    SCOM - Create Attribute - Create Group Wizard

  7. Under “Explicit Members” hit next, we don’t want to put anything in here.
  8. Under “Dynamic Members” click on Create/Edit Rules. From the drop down, select the class your attribute was added to (In this case, it’s Windows Server_Extended) and hit add to insert a line. Click on the drop down for Property, and you should see the one we created called “Notepad Running”.

    SCOM - Create Attribute - Dynamic Group Query Builder 2

    SCOM - Create Attribute - Dynamic Group Query Builder 2

  9. Select it, then finish up the formula. In this particular case we’re using “Greater than or equal to” as the operator and “1″ as the value.

    SCOM - Create Attribute - Dynamic Group Formula

    SCOM - Create Attribute - Dynamic Group Formula

    To be perfectly honest, you should consider this more of a ‘hack’. What happens is the agent runs “Select * FROM WIN32_Process where Name = ‘notepad.exe’” and returns the Handle property back to the server. The Handle property will never be 0 (Except for the System Idle Process). So if notepad.exe is running on a particular server, it will always return a Handle greater than or equal to 1. If notepad.exe isn’t running on a server, this query returns $null for the handle, which evaluates to FALSE in out Greater than or equal to formula.

  10. Click on OK, then Next. Hit next on Subgroups and again on Excluded Members, then hit ‘Create’.

You’re finished. Wait some time for the new discovery to propogate fully, then right click on your newly created group and then “View Group Members”. And now you can interact with this group just like you’ve always been. Have fun!

Posted in Authoring, SCOM, WMI | No Comments »

Not sitting on my laurels.

Posted by Jeremy D. Pavleck on 5th August 2008

It’s been awhile. I’ve actually been terribly busy at my current client, implementing and fine-tuning my Alert Resolution State notification workflow. I’m currently expanding it to hold a few dozen different teams, as well as creating PropertyBags to send performance data (Number of alerts changed per category, total time script ran, total alerts, etc) as well as addming more robust failure checks - that way it can also alert if it fails for any reason.

I’ve also been playing around with PowerShell and 37 year old code.

Super Star Trek - in PowerShell!

Super Star Trek - in PowerShell!

Yes, that’s Super Star Trek. Just a little time-waster I work on while I’m mulling over a problem or two. And huge thanks to Jaykul of course, for all of his Powershell knowledge. I can’t do it without him and the crew in #powershell!

Are you on Twitter? If so, be sure to follow OpsMgr to stay on top of the most recent SCOM posts out there! And while you’re at it, feel free to follow me as well - I can always use more friends.

Until next time.

Posted in Community, Powershell, SCOM | 2 Comments »

Twitter Updates for 2008-08-04

Posted by Jeremy D. Pavleck on 4th August 2008

Powered by Twitter Tools.

Posted in SCOM | No Comments »

A SCOM agent on your SmartPhone?

Posted by Jeremy D. Pavleck on 10th July 2008

Mayyyyyybe. I’m not saying anything 100% right now, but lemme say - wouldn’t it be so creepy and big brotherish if you had a SCOM agent on your SmartPhone, grabbing your current co-ordinates every 15 mins via GPS and then sending it to the RMS wirelessly?

But man, just how do we shoe horn an agent on poor Windows Mobile?

Just wait.

Posted in SCOM | 2 Comments »

Setting agent failover servers & Switching SNMP device proxies

Posted by Jeremy D. Pavleck on 7th July 2008

By default, you can’t really specify a failover management server in OpsMgr. Why? Not really sure, though I think it’s a ploy to ensure you setup the OpsMgr Active Directory Integration, which will handle this for you.

No fret though, we can still do it - it’ll just take a little bit of actual effort.

First, we need to define our Primary and Failover management servers. This isn’t something you can just progmatically grab, so you’ll need to know the name yourself.

In my $PROFILE, I’ve set them to be defined to 2 variables with the following:

# Set Primary Management Server
$Primary_MS = Get-ManagementServer | ? {$_.Name -like "SERVERNAME*"}
# Set Failover Management Server
$Failover_MS = Get-ManagementServer | ? {$_.Name -like "BACKUPSERVER*"}

Now that we have that set, it’s simple to do the rest. First, lets grab all of the servers that don’t have a failover management server set.

$noFailoverSpecified = Get-Agent | ? {(!$_.GetFailoverManagementServers())}

What the above does is call the GetFailoverManagementServers() method on each agent. If they have a failover, it will return data and thus $True. If there aren’t any failovers, it will return nothing - which is the same as $False. So we look for all the ones that don’t return anything.

If you’re curious, you can see just how many servers are missing failovers with

$noFailoverSpecified.Count

- in my case it was 63.

Now, we just run a quick snippet that adds the failover server to the agent:

ForEach ($agent in $noFailoverSpecified) {
Set-ManagementServer -PrimaryManagementServer $Primary_MS -AgentManagedComputer $agent -FailoverServer $Failover_MS | Out-Null
}

That will crunch away as it’s doing it’s thing, we’re redirecting output to $null so we don’t have to see agents scrolling over and over. When it returns you to a prompt, you’re done. If you’d like to verify that you did indeed set all of the agents to have a failover, we can check real quick:

If ((Get-Agent |? {(!$_.GetFailoverManagementServers())}).Count -eq $null)
{
Write-Host "Every agent has a failover server, great job!" -ForeGroundColor Green
} else {
Write-Host "Looks like we missed some, try again!" -ForeGroundColor Magenta
}

And that’s that. All of your agents have a primary and failover server.

Screen shot of SCOM Command Shell showing steps to setup failover agents

But wait, you have a lot of remotely managed devices too? Monitoring SNMP on a bunch of different servers - what happens for that?

Well, we can’t setup a failover (From what I’ve seen, if I’m wrong please let me know) agent. But we can proactively write a script that will change the proxy agent on the devices, and run it as needed.

This was written in a response to this query on the newsgroups, and is only a cursory look into it. There may be other ways of doing this - and I’d love to hear it. As it stands, I’m not sure how to set them back to a management server as the monitor.

Firstly, we’ll have to pick an agent managed computer to use as the new proxy agent. You can’t use a management server for this, because they aren’t “Agent Managed” and you can’t use Set-ManagementServer because the devices aren’t “Remote Managed Computers”.  I have a seperate agent-managed server on my network I call “Timex” because it acts like a watcher node. So I’ll go ahead and use him.

$proxyAgent = Get-Agent |? {$_.Name -eq "timex.pavleck.net"}

Then gather a list of our current remotely managed devices

$remDevices = Get-RemotelyManagedDevice

Now just loop through it, setting the device to use the proxy agent we just instantiated:

ForEach($device in $remDevices) {
Set-ProxyAgent -ProxyAgent $proxyAgent -Device $device | Out-Null
}

That will loop through things changing the proxy server that it uses. When it’s done, we can verify it by running:

Get-RemotelyManagedDevice |? {$_.ProxyAgentPrincipalName -ne $proxyAgent.Name}

If it outputs nothing, then they’ve all been changed. Simple as that!

SCOM: Setting the proxy agent for a device via command shell

Posted in Command Shell, Powershell, SCOM, SCOM Snippets, SNMP | 2 Comments »

Using Resolution States to fine tune alert notifications

Posted by Jeremy D. Pavleck on 3rd July 2008

I haven’t seen this solution offered as a way to send more customized alerts, and am fairly excited about it. With some of the previous solutions, they involve using the command shell to create an alert notification. This is fine, except if you open the subscription in the GUI - once you’ve done that, you’ve essentially undid all that work and created a ‘catch all’ that sends an alert on any event. Why? Well, the GUI itself isn’t designed for the custom settings that can be done in Powershell. This makes it fairly difficult to add people or change the alert - not acceptable to me.

After messing around with authoring console and creating classes based on event viewer errors and other equally exotic methods I came upon something that works wonderfully. The catch? You can only create 254 rules this way.

What am I talking about? Some powershell scripts and the alert resolution states!

SCOM Administration MG Settings - Alerts

By default, there are only 2 states defined - 0 for New, and 255 for Closed. They are always there, and can not be deleted. This leaves 1 - 254 as user definable states. We can use these to make one-to-one events.

Let me start off that this isn’t an ideal solution, but it is the most readable and elegant solution for this particular problem. You probably shouldn’t do this on a single rule basis, but target it more at a wildcard match. You do have a naming convention for your rules and monitors, right? If not, this is the perfect reason to get one. I’ll typically use a convention of <Product Type>-<Product>-<Version (If multiple)-<Rule>. So if I had a rule targeted at exchange, I’d have a rule similar to “EMAIL - Exchange - Exchange 2007 - Search for ‘Jeremy is fired’ in execs mail”. Then when I’m using an exotic config to send an alert, such as this one, I can better fine tune alerts.

Remember, the more you move away from the  “Out of box” yfunctionality with OpsMgr, the more you should be documenting. Or even better, a wiki. Just make a reference to the wiki in the description, and people will know exactly what you’re trying to do - that’s for another post though.

Let’s get on with it, shall we?

I’m going to create a situation. I have a custom application which logs to the Application log. There’s one particular event that only one group in the organization cares about - all they want is a notification of this one single event and nothing else. How do we do it?

The Cliff’s Notes version of what we’ll be accomplishing today:

  • Create a custom Resolution State
  • Define a new rule
  • Deploy a PowerShell script to the RMS to update the resolution state of matching alerts
  • Create a notification subscription which responds to our particular state

Now, for the complete steps

  1. First go to Authoring > Management Pack Objects > Rules - Right click and “Create new rule”
  2. Under rule type, select Alert Generating, Event Based, NT Event Log (Alert) and select a management pack to use.
    System Center Operations Manager 2007 Creat Rule Wizard
  3. Enter a rule name that is distinctive enough that no other rules will have that same name.  Then enter a description, rule category and choose a target. You can go with the shotgun approach and pick “All Computers” here if you’d like.
    SCOM - Authoring - Create Rule Wizard
  4. Now walk through the rest of the wizard and configure your event log settings - for this test I’m using the Application log, Event ID of 926 and event source of “Pavleck.NET Test”. But you can put whatever you want here ace, it’s up to you.
  5. Configure your alert. It should automatically copy over the rule name as the alert name. The alert name is what we’ll actually be alerting on, so it’s important that you remember what it is, and ensure it’s distinctive enough to not match something that already exists.
    SCOM - Authoring - Create Rule Wizard - Configuring the alert
  6. Now we can work on the other parts of this while our rule is propagating across the environment.
  7. Go to Administration > Settings > Alerts - this is where we’ll define a new Alert Resolution State to use. Click on “New…” and name your state and choose an ID for it, I used 10 in this example.
    SCOM - Alert Resolution States - Adding a new state
  8. Click Apply, then Ok and now we’re done with part 2.
  9. Let’s go ahead and test and see if our rule works, just open a command window and use some EventCreate.exe magic.
  10. Open up the alert console for whatever machine you ran that on and you should see our new alert in there - yay, we did something!
  11. Now we’ll add the magic that changes the alert resolution state. It’s a fairly simple script, and it’s meant to be that way. For simplicity’s sake, we’ll be running this script as a timed response from the RMS. Depending on how your particular environment is setup, you could also run it inside of the rule itself, as an additional response to “Create Alert”. But that only works well if you only plan on doinbg this sparingly, otherwise it makes more sense to run this from the RMS and add onto the script as needed.
    First, download SCOM-UpdateResolution.ps1 here (Or view it after the jump) and edit the alert name, resolution state and RMS to what matches your environment.
  12. Now we’ll need to go and create a new rule. Rule type is Timed Commands > Execute a command. Give it a name and description. I’ve set the rule category to “Maintenance” as that makes the most sense to me.
  13. For the schedule, I’ve set mine to run every 2 minutes. This means there will be a delay of that much between alerts and notifications, but that’s acceptable to me. Then hit next.
  14. Configure the command line execution settings as shown - remembering to use “&” instead of “&”. I’ve set the timeout to 45 seconds.
  15. Hit create and that’s almost all of it - all we need to do now is to create the alert subscription. Go to administration, right click on Subscriptions and choose “Create new notification subscription”
  16. Step through it like normal, choosing all groups, all classes. When you get to the Alert Criteria page, uncheck “New” and “Closed” and check our new resolution state. If you keep ‘closed’ in there, it will pertain to all alerts that close. That’s one drawback to this method, you won’t get closed alerts.
    Alert Criteria Pane of the Notification Subscription wizard, showing our custom resolution selected
  17. Finish it up as you normally would, then lets test it! Create a few more test events, and lets see if it works.

That’s all there is to it. This works, reliably and 100% of the time. It’s extremely flexible and easy to follow for someone just walking into your environment.

By using a single PowerShell script, and targeting the RMS computer group you’ll be making sure that you have only a single simple script to edit and by mirroring the files and directory paths to any other management servers in your environment you maintain this method if you ever need to promote one to an RMS.

Read the rest of this entry »

Posted in Authoring, Notifications, SCOM | 3 Comments »

Refresher Course: Moving management packs from MOM 2005 to SCOM 2007

Posted by Jeremy D. Pavleck on 26th June 2008

This is just a refresher course on how to convert an MS Operations Manager 2005 management pack into an OpsMgr 2007 management pack. It’s not tough, but I’m doing it so I figure I might as well document it!

1. Open your MOM 2005 Administration console, click on “Management Packs”, then select “Import/Export Management Packs” in the right hand pane.

2. Go through the wizard, selecting the export option, and choosing the rule group you’re looking for. You can choose to export views and tasks as well, but I recommend against that as it’s easy enough to recreate in OpsMgr and you have a lot more objects to choose from. Give it a file name - I usually use <Rule Group>.MP.2005 to make it obvious where it came from.

3. Next you’ll want to make sure you have the MOM 2005 Resource Kit installed on your management server and go to %PROGRAM FILES%\Microsoft Operations Manager Resource Kit\Tools\Convert Management Packs to XML. Copy the file MP2XML.exe to the same place you exported your management pack to.

4. Now get to that location via the command line, and lets take that binary AKM and make it useful. Converting it is pretty straightforward - just run MP2XML.exe MOM2005ManagementPack.akm MyNewXMLFile.xml.

Screen shot of MOM 2005 RK MP2XML

5. When it’s done, copy that new MOM 2005 XML document into your SCOM directory. In that directory lie 2 tools we need, MPConvert.exe and MPVerify.exe. You can copy these tools somewhere else if you like, but the verification tool needs access to other management packs so make sure it’s in your %PATH% otherwise.

6. Run MPConvert.exe against your XML file. The tool is looking for MPConvert.exe OLD_NAME NEW_NAME. For simplicity’s sake I use the same name, only appending _converted to the end to differentiate the 2.

Running MPConvert.exe against an XML file

7. When that’s done, run MPVerify.exe against the new managment pack. What this tool does is ensure that everything has been converted over to the new format properly. It’s as simple as MPVerify.exe New_Management_Pack.xml

Running MPVerify.exe against a newly converted management pack

8. From there, it’s up to you. You can open the new unsealed management pack in the Authoring Console to adjust things, or you can just import it in as it is - the choice is yours! That’s all there is to it!

Newly converted management pack imported into SCOM

Posted in MOM, Migration, SCOM | 3 Comments »

A ‘consoleless’ OpsMgr

Posted by Jeremy D. Pavleck on 23rd June 2008

In MOM 2005, virtually everything was a rule. A rule looked for an even in the event viewer, a line in a log file, a return code from a script, etc and fired off an alert (Or did another action). It was essentially ‘dumb’, because it had no idea whether or not if an even it raised was ever fixed. It just fired them off every time it saw it.

Enter OpsMgr 2007. It introduced us to an old concept of the ‘monitor’. The monitor is a multi-state event. It watches for multiple items; something will set a particular item into a failed or degraded mode, and there is a corresponding event that marked it as being healthy again. This is wonderful, as it helps minimize the amount of open alerts sitting in your system at any given time. Less open alerts means we have more relevant information to look at.

When it comes to core Windows monitors, it works beautifully and 100% of the time. If you cross a memory threshold, an event is created and an alert goes out (If you’ve set it up to alert). When the memory drops below this threshold, then the monitor marks that particular object as being in a Healthy state again and, if you’ve allowed it to, it auto-closes the alert.

When this doesn’t work beautifully and 100% of the time is when you need to rely on 3rd party agents and management packs. I’ll use the HP Management Packs as an example, because that’s what I’ve been facing recently.

The way OpsMgr knows about hardware events that happen on an HP machine is because the HP agents themselves will place an event in the Event Viewer and/or send an SNMP trap about it. Works flawlessly to create an event in SCOM about an unhealthy object. What doesn’t work perfectly is the corresponding event that marks that system as being healthy again.

The reason for this seems to depend on the exact configuration of a server, the version of the HP agents, and the actual event itself. If there is an event, such as a power supply failing, the log is populated and SCOM creates an event saying “Power Supply #1 degraded.”. When that power supply is replaced, it won’t necessarily auto-resolve the event, because instead of seeing “Power Supply #1 Healthy”, the HP agents might instead log “Power Supply (Serial number: FD30401104-P) Inserted into Bay #0″. The monitor isn’t looking for that, and so it isn’t aware that that is the corresponding ‘good’ event, and the event stays open.

So theoretically you could replace a failing piece of hardware, such as a Power Supply, which doesn’t auto-resolve and then in the future have that same PSU die, which won’t cause a new alert and literally leave you ‘powerless’ to know what is going on.

Now, in a normal deployment of OpsMgr this isn’t to large of a concern. There are always eyes on the console or emails being sent. Someone will see it, fix it, then ensure the event is closed.

The current situation I’m in, however, doesn’t work this way. SCOM is being used consoleless to monitor a group of monitoring tools. Essentially it’s here to keep ‘them’ honest, and to ensure there’s another level of defense to protect us and let us know when a failure has occurred.

Because of this, those slight discrepancies in the HP agents and the HP management pack aren’t acceptable. But OpsMgr really doesn’t have a way of being run without anyone paying attention to it - or does it?

It actually does. What I’ve setup at this site is a PowerShell script which runs every 4 hours and resolves all the open HP alerts.The HP Agents themselves will run a self-check every hour or so, and log that “Power Supply #1″ is still failed. Because we’ve already cleared that alert, SCOM will pick it up again and re-fire the event, the alert, and all that jazz. In essence, we’ve created a ‘nag’ feature in SCOM.

This is beneficial in our case, because the current setup of OpsMgr where I’m at is mainly there to watch the other monitoring tools. This ‘nag’ lets us know that the problem was either not taken care of, or was not alerted on - thus ‘keeping them honest’.

How we do all this is very simple - the OpsMgr Command Shell has almost everything we need.

We’ll use Get-Alert to bring back a list of all open HP events, and Resolve-Alert to close them, adding a comment that we automated this.

To find the HP alerts, we need to match against the MonitoringObjectFullName property inside the alert. Through trial and error, I noticed that every single HP object began with “HewlettPackard”. So we’ll match against that, picking all alerts that don’t have a resolution state of 255 (Closed).

From there, we cycle through the alert array, passing each one to Resolve-Alert, along with a -comment - in my case I used “Closed by Powershell - see (link) for more details” with a link to the internal Wiki.

And that’s really all that there is to it. Mind you, I’ve done a lot more in the script, as you’ll see below. It measures how long it took to bring up the alerts, counts how many were per severity, the repeat count, etc then creates a PropertyBag and submits all the information to OpsMgr for reporting. It then also logs it to the eventviewer.

Download SCOM-Resolve-HardwareAlerts.ps1

This script is best setup to run every 4 hours or so. It’s setup as a generic ‘timed script’ inside of SCOM. If you’d like more info on setting up SCOM to work with Powershell more properly, see Brian Wren’s post here.

Here’s the script:

# ==============================================================================================
#
# Microsoft PowerShell Source File — Created with SAPIEN Technologies PrimalScript 4.1
#
# NAME: SCOM-Resolve-HardwareAlerts.ps1
#
# AUTHOR: Jeremy D. Pavleck , JPavleck@GMail.com
# DATE  : 6/11/2008
#
# COMMENT: When run, will gather all open HP alerts and mark them as resolved, setting a user
#    defined comment as well. It will then log to the event viewer it has done so.
#
# NOTES: The "Object Name" we use to determine what rules we want to resolve comes from the
#    MonitoringObjectFullName field of Get-Alert.
#    Also, you’ll need to either set this command to start in your SCOM2007 dir (By default
#    C:\Program Files\System Center 2007 or edit Microsoft.EnterpriseManagement.OperationsManager.ClientShell.Startup.ps1
#    in said directory and change the dot source reference from current directory to the complete path.
#
# When calling this from an OpsMgr scheduled command, use
# powershell  -PSConsoleFile "C:\Program Files\System Center Operations Manager 2007\Microsoft.EnterpriseManagement.OperationsManager.ClientShell.Console.psc1" -command "&amp;amp; {C:\Script\Path.ps1}"
#
# ==============================================================================================
# Ensure that the OpsMgr snap-in is there
Get-PSSnapin -name Microsoft.EnterpriseManagement.OperationsManager.Client -ErrorAction SilentlyContinue
If (!$?) {
throw "OpsMgr Console not loaded - please run with -PSConsolfile ‘X:\Path\To\Microsoft.EnterpriseManagement.OperationsManager.ClientShell.Console.psc1′"
} else {
# CHANGE THIS to match the path in your system. Or don’t.
. "C:\Program Files\System Center Operations Manager 2007\Microsoft.EnterpriseManagement.OperationsManager.ClientShell.Startup.ps1" # Load OpsMgr stuff.
}

# Create some counters
$iinfo = 0
$iwarn = 0
$ierr = 0
$icrit = 0
$iunk = 0

### Configuration Section ###
$objectName = "HewlettPackard" # All of the HP objects start with this
$comment = "Automatically Resolved via PowerShell" # Added to alert

# Create the SCOM Script API object, so we can shove this info into the database
$momapi = New-Object -comObject "MOM.ScriptAPI"

# Grab all alerts that match MonitoringObjectFullName and are not Closed
# Time the whole thing for no reason
$findAlertsTime = Measure-Command {
$openHPAlerts = get-alert | Where-Object {
($_.MonitoringObjectFullName -match $objectName) -and ($_.ResolutionState -ne 255)
}
}

# Let’s grab some stats about what we grabbed first, before we resolve them.
$openCount = $openHPAlerts.Count
$totalFindTime = ([datetime]($findAlertsTime.ticks)).ToString("HH:mm.ss")
# Create a property bag to hold values to send to SCOM
$pbag = $momapi.CreatePropertyBag()
$pbag.AddValue("Total_Open", $openCount)
$pbag.AddValue("Total_FindTime", $totalFindTime)

# Resolving them couldn’t be simpler
# Lets count the severities we’re clearing, though.
foreach($alert in $openHPAlerts)
{
switch ($alert.Severity) {
"Information"     {$iinfo++}
"Warning"         {$iwarn++}
"Error"            {$ierr++}
"Critical"        {$icrit++}
}
$progress += "Server: " + $alert.NetBiosComputerName + " - Rule ‘" + $alert.Name + "’ - Repeat Count: " + $alert.RepeatCount + " `n";
# $pbag.AddValue("AutoResolveFor", $alert.NetBiosComputerName)
resolve-alert -comment $comment -Alert $alert
}

$pbag.AddValue("Info_HP_Alerts", $iinfo)
$pbag.AddValue("Warn_HP_Alerts", $iwarn)
$pbag.AddValue("Err_HP_Alerts", $ierr)
$pbag.AddValue("Crit_HP_Alerts", $icrit)
# Submit property bag to SCOM
$momapi.Return($pbag)

# Log eventviewer event to let us know what we did
# Severities: 1 = Error, 2 = Warning, 4 = Informational - "Script Name", "Event ID", "Severity", "Description"
$momapi.LogScriptEvent("SCOM-Resolve-HardwareAlerts.ps1", 926, 4, "Successfully resolved " + $openCount + " alerts. `nReport:`n" + $progress)
 

Posted in HP, Powershell, SCOM | No Comments »

Great list of SCOM & MOM Bloggers

Posted by Jeremy D. Pavleck on 16th June 2008

Ian Blyth of the System Center Technologies blog has put together a quite extensive list of MOM & SCOM bloggers. I encourage you to check em out and add their feeds to your feed reader - and to make it even easier on you, I’ve created 4 OPML feeds for you to choose from. They’ve been lumped into 3 groups; MS Blogs, Community Blogs, and Useful Feeds. Most newsreaders allow you to choose which links you want to import from a feed, and they are in folders, so choose the grand list first and if that doesn’t work, try one of the other ones.

SCOM & MOM - All Feeds.opml

SCOM & MOM - MS “Official” Feeds.opml

SCOM & MOM - Community Feeds.opml

SCOM & MOM - Useful Feeds.opml

Posted in Community, MOM, SCOM | 1 Comment »

SP1 Gem: Finding rules running on remote agents

Posted by Jeremy D. Pavleck on 13th June 2008

Remember in MOM 2005 the ease at which you could find out exactly what rules were running on what agent? It was as simple as going to Administration > Computers > Agent-managed computers > RIght-click on the server you’re interested in, hit properties then the “Rules” tab and bam:

Showing rules deployed to an agent in MOM 2005

In OpsMgr, it’s not quite so east. Sure, there are a ton of powershell commandlets available to help you figure it out - I think. I haven’t quite managed to get the correct order of Get-Agent, Get-MonitoringObject, Get-MonitoringClass, Get-Monitor, Get-Rule to produce a successful listing of what runs on a particular agent. I’m fairly positive it has to be there, I just haven’t found it1. So it was a tad difficult to find out what was running on a SCOM2007 agent.

Well, until Service Pack 1 RTM came around, that is. Located in UpdateCDImage\SupportTools folder is a management pack called “Microsoft.SystemCenter.Internal.Tasks.mp”. Go ahead and import it into your OpsMgr installation. I’ll wait right here.

Finished? Excellent. Now go to the Monitoring tab of the OpsMgr console and select “Computers” under Monitoring. Under the Windows Computer Tasks on the right side, you should see 4 new ones.

New Tasks!

The new tasks are

  • Resubmit local cache state change events
  • Show Failed Rules and Monitors for this Object
  • Show Local Cache for State Change Events
  • Show Running Rules and Monitors for this Object

What we’re most interested in is the “Show Running Rules and Monitors for this Object” task.

Click on it, submit the task, wait for it to crunch for a little bit and then you’re presented with an excellent little screen like below:

Pretty nice, eh? A complete, valid XML document listing the rules & monitors (Called ‘Workflows’ in this case) running on the agent.

Now, let’s PowerShell that up a bit - you can pull out all that information from within the Command Shell, in a nice little function.

Oh also, while we’re on the subject, I’ve found the super super easy way to determine which agent a HealthService ID belongs to. I know my previous result used raw queries to the SQL database and all that jazz, but not this one. Ready for it? If you blink, you might miss it. Here it is!

(Get-MonitoringObject -id "HealthService ID Here").DisplayName

Yep, it’s that easy. The wonders of powershell, eh?

Anyway, to run this task on an agent from within powershell, we have to do a little more work, but it’s really not all that bad.

Function Get-ActiveRules has 2 arguments: -server and -location. Server is self-explanatory, and it’s written to not require a FQDN; if your server is MYSERVER01.midwest.dc02.company.com, you just need to use MYSERVER01. The second argument is a location and filename for the output XML file. If left blank, it defaults to making C:\$server-rules.xml.

The is virtually no serious error checking, and it just dumps the Task OutPut field to an XML file instead of doing any magic with it, so it’s nothing fancy - take it as it is.

Enjoy! Download Get-ActiveRules.ps1

## Get-ActiveRules grabs the workflows running on the specified server
function Get-ActiveRules ([string]$server, [string]$location) {
If (!$location) { $location = "C:\$server-Rules.xml" }
# Create the Task object
$taskobj = Get-Task | Where-Object {$_.Name -eq "Microsoft.SystemCenter.GetAllRunningWorkflows"}
# Make sure we have it, if not, the MP isn’t installed.
If (!$taskobj) {
Write-Host "Unable to find required monitoring tasks - MS System Center Internal Tasks MP needs to be installed." -ForeGroundColor Magenta;
break;
}
# Grab HealthService class object
$hsobj = Get-MonitoringClass -name "Microsoft.SystemCenter.HealthService"
# Find HealthService object defined for named server
$monobj = Get-MonitoringObject -MonitoringClass $hsobj | Where-Object {$_.DisplayName -match $server}
# Now actually proceed with the task. I have mine formatted like this version, but I’ve added some light
# error checking for the ‘public’ version.
#(Start-Task -task $taskobj -TargetMonitoringObject $monobj).Output | Out-File C:\$server-Rules.xml
$taskOut = Start-Task -Task $taskobj -TargetMonitoringObject $monobj
# See if it worked, if it did, export out the OutPut part and save as an XML file, then display some items.
If ($taskOut.ErrorCode -eq 0) {
[xml]$taskXML = $taskOut.OutPut
$ruleCount = $taskXML.DataItem.Count
Write-Host "Succeeded in gathering rules for $server" -ForeGroundColor Green
Write-Host "Currently $ruleCount rules active." -ForeGroundColor Green
Write-Host "Exporting to $location" -ForeGroundColor Green
$taskOut.OutPut | Out-File $location
} else {
Write-Host "Error gathering rules for $server" -ForeGroundColor Magenta
Write-Host "Error Code: " + $taskOut.ErrorCode -ForeGroundColor Magenta
Write-Host "Error Message: " + $taskOut.ErrorMessage -ForeGroundColor Magenta
}

} # End Get-ActiveRules
#######################

  1. If you happen to know, please tell me! []

Posted in Powershell, SCOM | No Comments »