ENHANCED SCOM Alerts Notification Emails!

17/08/2012: The version 2 of this script has just been released: http://blog.tyang.org/2012/08/16/scom-enhanced-email-notification-script-version-2/

29/01/2012: The command notification channel setup section of this blog has been updated. More details of the change can be found HERE: http://blog.tyang.org/2012/01/29/command-line-parameters-for-scom-command-notification-channel/

Please Note: This post and associated script has been updated on 30/09/2010.

Even though SCOM is a great product, I personally believe that alert notification emails is something that really needs improvements. It is very hard (and almost impossible – according to my standard) to configure a meaningful notification email using the variables SCOM provides.

Most of times, the SCOM administrator would include a URL that takes you straight to the alert using SCOM web console. Web Console is greatly improved in SCOM 2007 R2, and it pretty much contains everything about the alert (such as alert name, description, source, time raised, monitor/rule name, description, knowledge article, etc).

image

But why can’t we have all this information in the notification email so we don’t have to come to the web console?

This cannot be done natively using SMTP notification channels. I accomplished it almost 2 years ago for my previous employer, using PowerShell and SCOM Command Notification Channel. I wrote a PowerShell script to utilise System.Net.Mail classes to send out HTML formatted email that contains EVERYTHING that you can get from SCOM Operations Console or Web Console.

The following information is included in the notification email:

  • – Alert name, description, severity, resolution state, source, path, Time created
  • – Monitor / Rule name
  • – Knowledge Article for the particular monitor / rule
  • – Web console URL link to the alert
  • – PowerShell command to retrieve the alert from SCOM command console

I completed forgot about this script until recently one of my customer’s support team asked me if there are any better ways to configure Alert Notification emails in SCOM. Now I’ve decided to post it in my blog so you all can benefit from it.

Below is the email notification for the alert from the above web console screenshot:

image

OK. if you want to try this out in your SCOM environment, please keep reading. Let’s go through the steps setting this up in SCOM:

1. Download SCOMEnhancedEmailNotification.ps1

2. Modify this section of the script (line 26-48, Highlighted in Yellow):

image

  • $NotifiedResState – At the end of this script, after the email is sent, it changes the resolution state of the alert to “Notified”. I have manually created such resolution state using SCOM Operations Console with number 85. You can use other number if you wish, just make sure this variable represent the right number of the resolution state you want the script to set the alert to at the end.
  • Function getResStateName – Modify function getResStateName to have ALL the resolution states for your SCOM environment.
  • $strSMTP – The FQDN of your SMTP server
  • $iPort – Port used for SMTP. default is 25. if your SMTP server is not use port 25, please change this variable accordingly.
  • $Sender – make sure you have the sender (return address) and the display name set inside the bracket( )
  • $ErrRecipient – If the script is running into errors, it will try to email the error message to this recipient. I’d suggest you to set this to your company’s SCOM administrator so they know there is a problem.

3. Once the script is modified, save it to a local folder on your RMS server. In this blog, we will use D:\Scripts\ as an example.

4. Setting up SCOM Command notification channel:

NOTE: Because we are not using SMTP channels, we cannot specify the email addresses in Subscriber’s properties. Instead, we are passing in the email addresses as parameters. So for subscriptions with different subscribers, you will need to create multiple command channels with different email addresses.

image

Settings:

  • Full path of the command file: C:\Windows\System32\WindowsPowerShell\v1.0\Powershell.exe
  • Command line parameters: -Command “& ‘”D:\Scripts\SCOMEnhancedEmailNotification.ps1″‘” -alertID ‘$Data/Context/DataItem/AlertId$’ -Recipients @(‘Tao Yang;Tao.Yang@xxxx.com’,John Smith;John.Smith@xxxx.com‘)
  • Note:
    1. Recipients are passed into the script as an array variable. make sure you use this format inside the (): Recipient 1 Name;Email’,’Recipient 2 Name;Email
    2. Alert ID is quoted using single quotation mark ONLY.
  • Startup folder for the command line: D:\Scripts
  • This is the location of the script

5. Setting up subscribers

Subscriber1

Subscriber2

Subscriber3

Subscriber address:

image

6. Setting up subscriptions

Subscription3

Subscription4

One last thing to remember: The powerShell execution policy on your RMS needs to set to RemoteSigned or Unrestricted.

This script can be downloaded HERE. Feel free to email me if you are having issues setting this up!

89 comments

  1. I’ve used this enhanced email notification powershell script, created the ‘Notified’ resolution state. But after setting an alert to ‘Notified’ resolution state I’m not getting emailed. Can you help if I’m missing something here? I’m using SCOM R2

    1. Changing the resolution state to “notified” is the last step of the script. Did you configure the SMTP server correctly? Did you configure the error recipient in the script? if so, did you get any emails sent to the error recipient? Also, you can use the Test-SMTP from this blog to test the SMTP server.

      If you still can’t figure out the problem, could you email me your modified script and screen shots of your command channel and subscription settings? I’ll take a look for you.

      Good luck.

  2. I am receiving errors from Unix systems when a new alert is generated with a “0” only on a few monitors:

    AIX 5.3 – Logical Disk % Free Space
    AIX 5.3 – Disk is not Online

    It says that the Resolution state has to be New (0) or the script will not process correctly.

    I have tried running the script:

    get-alert -Id “e6234cbc-97c8-41d4-91d8-a42824734aa8” | format-list *

    and it is also stating that the ResolutionState is “0”.

    Any thoughts as to how to start troubleshooting this? I have manually changed the resolution state to “85” and then closed it to see if it woudl make any differance and no dice.

    Any help would be greatly apprieciated. Love the script BTW.

    -Jason

  3. Jason,
    How did you setup your subscription criteria? in there, you can choose only subscribe to certain resolution state. you don’t have to only subscribe to new alerts. it’s just i’ve coded the script to change the resolution state to 85 once the alert has been processed.

    1. I followed your instructions on setting up the command notifications channel for the PS script. I have found that any system that is reporting into OpsMgr and only displaying a NetBIOS name (not the FQDN), the script will fail. Doesn’t matter if it is a Windows or Unix agent.

      I have traced the alert and it is generating at a “0” within SQL and the OpsMgr Console. The Notification Command runs and errors out.

      Here is more info on the monitor and alert:

      Monitor: “Logical Disk % Free Space”
      The Path is being passed as “Server1\/c02data1”
      The Source is being passed as “/c02data1”

      By looking at the script, it appears to be erroring out on the split command “.” (From what I can see). Looks as if it is getting confused with the \/ values in the path.

  4. Hi all,
    using the nice script i found an error in the GetNetBiosName function. It simply doesn’t return the host name because the return value is set for $NetBiosName and not for $GetNetBiosName.

    After this little correction the script did the job dearly.

    Thanks Tao

    1. Here’s another option:

      #Get Computer name
      If ($alert.NetBiosComputername -eq $null){
      If(($alert.PrincipalName).IndexOf(‘.’) -gt 1 ) { #Most likely an FQDN
      $strAgentName = (($alert.PrincipalName).Substring(0,($alert.PrincipalName).IndexOf(‘.’))) #Strip name out of FQDN
      }
      Else{
      $strAgentName = “nodata” #What else can you do if no name info? Nada.
      }
      }
      Else
      {
      $strAgentName = $alert.NetBiosComputername
      }

  5. Is there any difference when configuring this on a clusterd RMS server install?
    I’ve received several alerts when executing:
    You cannot call a method on a null-valued expression. You cannot call a method on a null-valued expression. You cannot call a method on a null-valued expression. You cannot call a method on a null-valued expression. You cannot call a method on a null-valued expression. You cannot call a method on a null-valued expression. You cannot call a method on a null-valued expression. Cannot bind parameter ‘Id’. Cannot convert value “‘{2bda5bd0-b061-4c36-9b4d-c3f74e726582}’” to type “System.Guid”. Error: “Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).” Cannot find path ‘Monitoring:\*server*because it does not exist. System error. The user DOSIM000\MgrMOM2007Msa does not have sufficient permission to perform the operation. Cannot remove item C:\Scripts\error.log: Access to the path is denied.

    Thanks for your time.

    1. Dieter,

      Although I’ve never implemented this on a clustered RMS environment, I don’t think it will be any differences as long as the script is located on a shared storage. Regarding to your error, you will need to remove the single quotes which are inside the double quotes in alert ID.
      BTW, I’ve posted the udpated script yesterday, are you using the new one or the old one?

      1. I’m using the new one.
        The quotes are already gone. The error above is where I’m stuck at the moment.

  6. After some further testing and configuring I’m coming to this error:
    Microsoft.EnterpriseManagement.Common.UnauthorizedAccessMonitoringException: The user *Management Server Action Account* does not have sufficient permission to perform the operation. at Microsoft.EnterpriseManagement.DataAbstractionLayer.SdkDataAbstractionLayer.HandleIndigoExceptions(Exception ex) at Microsoft.EnterpriseManagement.DataAbstractionLayer.AdministrationOperations.GetSettings(IList`1 managedTypePropertyIds) at Microsoft.EnterpriseManagement.Administration.Settings.Refresh() at Microsoft.EnterpriseManagement.Administration.ManagementGroupAdministration.InitializeSettings() at Microsoft.EnterpriseManagement.Administration.ManagementGroupAdministration.get_Settings() at Microsoft.EnterpriseManagement.OperationsManager.ClientShell.SetDefaultSettingCmdlet.ProcessRecord()

    Do I need to grant the user extra permissions on the console / SQL?
    Thanks in advance for your time.

      1. I’ve resolved my issue with your pointers.
        Thanks for the feedback and efforts!

        Solution:
        Did a full review of my run as accounts and reconfigured it as local system.
        Now my event log is clearing up and this script is working.

  7. Hello,
    I’m using SCOM 2007 R2. I’ve followed all of your instructions (as far as I know), even used double quotes only around the parameter passed (“$Data/Context/DataItem/AlertId$”) for R2 version when I set up the command, as noted in the ps1 file comments.
    The script exists on the local drive (c:\scom_scripts) of the RMS server as instructed. The folder permissions allow access by all users and admins.
    However, it appears as though the script never runs.
    It seems as though there may be some problem with Powershell. I tried setting the execution policy to unrestricted as well as remote signed. I’ve tested the Test-SMTP script successfully, although it prompts me every time with
    “Security Warning
    Run only scripts that you trust. While scripts from the Internet can be
    useful, this script can potentially harm your
    computer. Do you want to run ?
    [D] Do not run [R] Run once [S] Suspend [?] Help (default is “D”).”

    I can’t find any errors in the event log. There is no error log created in the folder (c:\scom_scripts). What am I doing wrong?
    Thanks in advance.

    1. Sounds like your execution policy isn’t set correctly. if you use get-exeuctionpolicy, what do you see? are you using Powershell V2? if so, try “set-executionpolicy unrestricted -force:$true”

  8. I tried the command you suggested however that returned the policy to “unrestricted” which I’ve already tried. I set it to “bypass” as this removes the warning.

    Verision is 2.
    PS C:\SCOM_SCRIPTS> $host.Version

    Major Minor Build Revision
    —– —– —– ——–
    2 0 -1 -1

    This is on the RMS server. Again, there is nothing in the event logs relating to this. Where, specifically, in the event logs (2008 Server) should I be looking?
    The subscription is set up targeting the subscriber and channel exactly as you described in your screenshots above.
    It’s as if the command never runs, or so it would seem. Could this be a permissions issue on the folder and/or ps1 file? If so, what should the ntfs permissions be? …and wouldn’t something show up in the security event logs and also in the SCOM alerts (failure to send notification alert)?

    1. there won’t be anything in event log if you are not auditing failed object access. what if you manually run the script (just pick an alert ID from get-alert | where-object {$_.resolutionstate -eq 0})
      also, anything in the error.log in the same folder where you put the script?

  9. No error.log in the folder. I tried manually running the script once before without passing a parameter to it and it did create a log at that point, after which I deleted it.. but no log otherwise. I’ll try your suggestion and get back to you. Thanks again for your help.

    1. Update: It seems that the script WAS sending notifications for a while overnight and into the morning. .. then stopped. I got very excited and then cried myself to sleep on my keyboard. I tried your suggestion and the alert gets sent successfully when I run the script manually. So why wouldn’t the subscription be working consistently? So far SCOM is a bit of a bummer. Reporting services has been a bit of a nightmare as well. I’m still not giving up on it and I greatly appreciate your assistance. It’s people like you who give us little guys hope. 😀

      Also, in your example you show the Startup folder with a trailing slash but the SCOM channel wizard shows and example without a trailing slash. I know this shouldn’t matter… but I’m leaving nothing to chance.

      1. I deleted/recreated the subscripton and triggered some alerts, then emails started sending. I’ll keep you posted.

  10. For some reason the script will NOT write the error log to the directory. I have tried adding the action account and the runas service account to the NTFS perms of the script folder+ with Full Control. Still won’t write the error log. I get the error emails… but no log. 🙁 Any suggestions?

  11. I was trying to trigger errors on purpose to test if the script was able to generate the error log because I’m seeing that the script is very, very inconsistent. It will only run for about 25% of the alerts that occur. When it does run successfully, I receive the email notification and see that the status changes from New to Notified. I love the format of the email and the content but if I can’t get this to run 100% of the time for all alerts, I can’t use it and will be forced to use the terrible built-in notification channel. I’d love it if there were some kind of log entries anywhere to help diagnose why it’s so inconsistent. Do you want to take this offline, via email only?

    1. Do you get error emails for the other 75%? can you make sure your subscriptions are setup correctly?

      Also, it might be an indication that your RMS is running out of resources (CPU, memory). it might worth setting up perfmon for a period of time.

      Can we take this offline from the blog? Let’s use emails instead (you can find my email address from the “About” page).

      1. I had the same issue that only 20-40% alerts’ emails sent out. Do you find solutions or reasons? Thanks, ZL.

      1. I dug into this issue for a long time and was unable to get 100% consistency from the script/Powershell. I had to give up.
        The content and layout of the notification is absolutely beautiful. I just wish I could get it to cooperate fully. :/
        ~Tyson

  12. I stumbled upon this today and am having some issues. I’ve configured the channel, subscriber and subscription as outlined, however am not receiving e-mails through this channel for all alerts. I am getting all alerts through the SMTP channel however. I’ve tested the script with a valid Alert ID and it works so I’m not sure what may be wrong. I noticed that Tyson also had a similar issue like this, just wonder if there was a resolution for that.

  13. HI I used the script manually.
    still i dint get any email.

    i do get one error email that configured per script. (i corrected it by removing single quote marks and it dint errored thereafter but I dint get any mail either).

    mail goes as
    ===========
    E:\Scripts\SCOMEnhancedEmailNotification.ps1 -alertID “‘$Data/Context/DataItem/AlertId$’” -Recipients @(‘Manish Pawar;xxx@xxx.com’)

    Error occurred when excuting E:\scripts\SCOMEnhancedEmailNotification.ps1 located at xxxxx.com for alert ID ‘xxxxxxxx-xxxx-40a8-a921-17d629a12cbf’.
    Alert Resolution State:
    **Note:Error will occur if the script tries to process an alert with Resolution State other than New.
    You cannot call a method on a null-valued expression. You cannot call a method on a null-valued expression. You cannot call a method on a null-valued expression. You cannot call a method on a null-valued expression. You cannot call a method on a null-valued expression. You cannot call a method on a null-valued expression. You cannot call a method on a null-valued expression. Cannot bind parameter ‘Id’. Cannot convert value “‘xxxxxxxx-xxxx-40a8-a921-17d629a12cbf'” to type “System.Guid”. Error: “Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).”
    **Use below command to view the full details of this alert in SCOM Powershell console:
    get-alert -Id “‘xxxxxxxx-xxxx-40a8-a921-17d629a12cbf'” | format-list *
    SCOM link: ?LINK
    ==================

  14. hi
    i got the notification channel working for me by uisng following settings

    FULL PATH TO FILE

    c:\windows\system32\cmd.exe

    PARAMETERES (please look for the “” quotes properly)

    /c “”C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe” “”e:\scripts\SCOMEnhancedEmailNotification.ps1 -alertID “$Data/Context/DataItem/AlertId$” -Recipients @(‘xxxxx xxxxxxxxx;xxxxx@xxxxx.com’)”””

  15. Hi Tao Tang,

    I have my script working and sending out notifications.

    As i have to implement it in productoin env, i was testing it and found that the script is missing few alerts (ex 2 out of 10 alerts) and not senidng notification for them.

    How can we ensure that it got triggered at all alerts and should process all alerts.

    Any help is appreciated. 🙂 and many thanks for the script.

    Thanks
    Manish

  16. I should refine my question to be a little bit more specific, how do I use the agentid for a repeating alert but for different machines. To be clear:

    I have an Alert called AD Machine Authentication and multiple computers trigger that alert, but if I use the agentid I only get an email for that one machine. How do I get an email each time different machines trigger the alert?

    Thanks,

    Hewissa

    1. Hi Hewissa,

      AgentID is a built-in variable in SCOM notification. It is passed in to the notification channel by SCOM itself. alerts for a specific application are still generated from a SCOM agent (most of cases agent proxy setting needs to be enabled for that particular SCOM agent).

  17. Thank you for reply Tao, I thought I wasn’t going to get one since the post had been quite for a few months.

    How do I not use AgentID but instead use AgentName? I need to generate emails when an alert with a particular name is flagged? I have tried to modify your script contents to accept the Name of the alert but the error log just fills will Null value errors and such.

    1. sorry, you have to use AlertID as this is unique to each alert. what you can do is in the alert subscription, only subscribe to alerts generated from specific agent or group of agents.

  18. Just seen your post today, great blog btw….

    It’s nearly just what I need, I need this function but via an ‘Alert Task’

    We have the need to send ad hoc alert information to different people or teams and like the ability to have say a web team task we can click and it will trigger the e-mail using your script.

    Problem is I am not sure the best way to do this or even if I can get your script to perform this.

    I have had a look and as of yet not been able to figure out the best way to do this.

    So I bow to you for any insight you may have on this.

    Thanks
    Robert

    1. Hi Robert, the script can run manually as long as you know the alert ID. you can probably build a web page to display the alerts and call my script from it with the alert ID and recipients addresses.

      1. I was thinking of clicking an alert in the opsmgr console then having a task to the right to trigger the script somehow.

        Just not 100% on how.

  19. Hi Tao, Are you aware of any solution to the consistency problem that Manish and I are both experiencing? Any help would be greatly appreciated.

  20. UPDATE! I’ve discovered that the script fails if the AlertID begins with a number but is successful if it begins with a letter.

    This is the error:

    C:\SCOM_SCRIPTS>C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe C:\SCOM_SCRIPTS\SCOMEnhancedEmailNotification.ps1 -alertID “{5aee342c-0446-4a5c-955f-6bed3220f60d}” -Recipients @(‘Tyson;tyson@XXXXXX.com’)
    Bad numeric constant: 5.
    At line:1 char:62
    + C:\SCOM_SCRIPTS\SCOMEnhancedEmailNotification.ps1 -alertID {5 <<<< aee342c-0446-4a5c-955f-6bed3220f60d} -Recipients @('Tyson;tyson@XXXXXX.com')
    + CategoryInfo : ParserError: (5:String) [], ParentContainsErrorR
    ecordException
    + FullyQualifiedErrorId : BadNumericConstant

  21. SOLUTION!! The instructions are wrong.

    This is what the instructions say at the top of the script:
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    #In OpsMgr R1, the parameter passed in is “‘$Data/Context/DataItem/AlertId$'” (single quote inside double quote)
    #In OpsMgr R2, the parameter passed in is “$Data/Context/DataItem/AlertId$” (double quote)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    I’m using R2 and the double quotes DO NOT work. I have to use single quotes like this:
    ##################################################################
    1) %SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe

    2) C:\SCOM_SCRIPTS\SCOMEnhancedEmailNotification.ps1 -alertID ‘$Data/Context/DataItem/AlertId$’ -Recipients @(‘Tyson;tyson@xxxxxxx.com’)

    3) C:\SCOM_SCRIPTS
    …where 1,2,3 are full path to command line, parameters, and startup folder respectively. Notice the single quotes in #2 above.
    ##################################################################

    Tao,
    I’ve been banging my head on the desk for months over this one. Still, i LOVE this script. Thanks for taking the time to make it available to the rest of us.
    ~Tyson

    1. Thanks Tyson! I was having this exact problem and was on the verge of dropping the whole thing until I found this post. The script needs updating and/or your comment needs to be put at the top of the article.

      Tao – thanks for the script. It’s certainly eliminating some annoyances around here regarding notifications.

  22. Hello Tao,

    the script is working great for me..to good actually. I get an email notification everytime the alert is refreshed. So for a workflow that runs every minute, I get an alert every minute. It does not seem to understand that it’s is the same alert.

    What am I missing??

    thanks…

    1. Hector,

      How did you setup your subscription criteria? To troubleshoot, for the same subscription, what if you change it to normal SMTP channel, does it also email you every minute?

  23. Hello Tao,

    I figured it out. I try to get smart (lazy) and set the $NotifiedResState variable to zaro just so I wouldn’t have to create a new alert resolution state. that caused every alert to be re-set to New every single time. I have now created the approapiate states and it is working great.

  24. Hello,

    Thank you for the script it works perfectly but I am running into issue with knowledge base article. in the sealed management packs there are default knowledge article (product knowledge) and we add custom (company knowledge article) and in the email as a knowledge article it is showing default (product knowledge) article. Is it possible to change that? Make it to show the company knowledge first then product knowledge?

    Thanks.

    1. Hi Orhan,
      Currently the script does not retrieve company knowledge. but it should be pretty easy to add it. I’ll try to get the script updated in the next few days and post it here.

        1. Hi Orhan,
          I had a look the other day. Looks like there is no way to get Company knowledge using PowerShell SCOM snap-in natively. It might be possible using SCOM SDK (I haven’t really spent too much time to go down this path). Because this script runs on RMS everytime a subscribed alert is raised, we should really keep it simple to reduce the load on RMS. I wouldn’t make it much more complicated just to get the company knowledge.

          Cheers
          Tao

  25. Hi Tao,

    This is pretty cool. I got it to work without much effort. I wanted to know if I can remove the resolution state of closed in the script so I dont get emails for when an alert is closed manually? Basically I dont want to mess with SCOM connectors to remove “closed” on the connector level. Creating new connectors and then doing filters on the connector seem to produce unreliable SMTP alerts.

    So I was thinking that I could just remove “255” { $resStateName = “Closed” } from the function getResStateName and NOT get emails for the “closed” state.

    Would that work???

    Thanks for your time!

    1. Gene,

      if you don’t want to be notified when alerts are closed, you can simply modify your subscription criteria to not notify you when alert resolution state is 255. changing the script is not going to achive your goal and will only make it to fail.

  26. guess im being lazy…I can surely try it and just see what happens. I suppose I wanted your opinion as to what else it could break by not having all the res states defined in the script (IE: unforseen stuff).

    Perhaps you could shed some light on your way to stop closed alerts from going through notification?

  27. I thought I have posted a solution for an error I found on the script but I guess not.

    it is simple, some Alerts do not have a Principal Name parameter and thefore fail. after reviewing hundreds of alerts I think there are just one or two that fall into this category.

    To Address the issue I have added the following code:

    {
    if ($PrincipalName -eq $null)
    {
    $NetBiosName = ($MonitoringObjDisplayName.split(“.”))[0]
    }
    else
    {
    $NetBiosName = ($PrincipalName.split(“.”))[0]
    }
    }

    $NetBiosName
    }

  28. This is Simply great, Thanks for sharing this Tao Yang i tested it and it’s working perfectly fine only one modification is required in the scrip is for SCOM 2007 R2 as Tyson is suggested:
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    #In OpsMgr R1, the parameter passed in is “‘$Data/Context/DataItem/AlertId$’” (single quote inside double quote)
    #In OpsMgr R2, the parameter passed in is “$Data/Context/DataItem/AlertId$” (double quote)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    I’m using R2 and the double quotes DO NOT work. I have to use single quotes like this:
    ##################################################################
    1) %SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe
    2) C:\SCOM_SCRIPTS\SCOMEnhancedEmailNotification.ps1 -alertID ‘$Data/Context/DataItem/AlertId$’ -Recipients @(‘Tyson;tyson@xxxxxxx.com’)
    3) C:\SCOM_SCRIPTS
    …where 1,2,3 are full path to command line, parameters, and startup folder respectively. Notice the single quotes in #2 above.
    ##################################################################
    Rest is perfectly fine.
    Thanks once again.

  29. Can I set this up to also send a closed email when the alert has been resolved? I get the open but I would like the closed as well.

    1. Yes you can. firstly you’ll need to modify the script to not to update the resolution state at the end. then in subscription criteria, select resolution state of 255.

      1. Sorry I am still learning my powershell.. Would I change it here. ##Make sure the script is closed
        if ($error.count -eq “0”)
        {
        if ($alert.ResolutionState -eq “0”)
        {
        $alert.ResolutionState = $NotifiedResState
        $alert.Update(“”)
        }
        $host.setShouldExit(0)

  30. I love the enhanced notificatio. I deployed it with a modification to use it as a console task. I added to the script to include specific e-mail address as a drop down choice or a box to enter specific smtp address. I can send an alert as an e- mail directly from the alert view. Chuck Hughes

    1. Chuck, would you mind sharing how you were able to accomplish adding this as a console task? In particular I’m wondering how you were able to configure the drop down box and free text field for smtp address?

  31. First of all thanks for the script, I wanted to ask if I want to attach a picture (company logo), I enclose it as I am enclosing html page but where am I supposed to put the jpg file?
    thank roey

    1. Roey,
      I think you will have to put the jpg file on a web server and then include a hyperlink to the image in the email body (since it’s HTML based).

  32. Hi Tao,

    First of all many thanks for this script, it helped me a lot to improve email alerts quality!

    I’m using it since 5 months now and I’m fighting with some performance issues. Some times, especially when alert storm occure, I have some alert “Operations Manager failed to start a process”, “The process could not be created because the maximum number of asynchronous responses (50) has already been reached,”. As you probably noticed, I already set AsyncProcessLimit to 50. Moreover, I double checked quotation around alertID in parameter string, everything seems fine. Debugging a little bit more, I installed a local SMTP server to avoid delay in connection. Then I also added some debug output in the script and found that total execution time was very variable but most of the time very very very high, between 2 sec to 15 sec. This explain why AsyncProcessLimit is frequently reached. Have you ever noticed such kind of issue? I’ve tested on 3 different management servers, with win2008 and win2012, issue is always the same. Thank you for your help.

  33. Hi Tao,

    We use your script to target notification groups (containing email and SMS receivers)contained in a 3rd party app, this works great although the whole notification backend of SCOM is a little cumbersome! I have a question, do you know if referencing multiple channels in a subscription works? You can configure multiple channels and subscribers in a subscription I’m just wondering if it works though or does it stop processing alerts after the first subscriber and channel? I plan to test later today but was just wondering if you’ve done this already….?

    Cheers

    1. it depends how the subscriptions are setup – because this notification script changes the alert resolution state when it processes alerts. you might want to modify “NotifiedState” value in the config.xml file so it does not change the resolution state.

  34. Hi Tao,

    Following on from Davy’s comment, we added some code to the end of your script which takes the list of recipients and puts it back into one of the custom fields of the alert.
    Because we have two channels, when the second channel tries to update the alert in SCOM it fails due to the first channel already updating it. We have stopped the NotifiedState so the script doesn’t exit.
    Is there a way of delaying the channels so they occur sequentially instead of simultaneously?
    Or is there a way to get the name of the subscription which captured the alert and sent out the notification to the subscribers?

  35. sorry, i should have been more clear, within one subscription we have two subscribers and two channels. they both execute your script fine, but only one of them updates the information back to the alerts custom fields. so is it possible to put a delay on the individual subscriber/channel so that they happen one after the other?

  36. Allow me to give a bit more background and a practical example. The 3rd party notification software enables us to create notification groups containing the relevant SME’s who need to know when an issue occurs, these notification groups are made up of email and SMS receivers and can be different formats for handling varying support scenarios and criticalities, so one group could be an on-duty type to manage a 24/7 support cycle with different shifts, another may be an on-call escalation group where there’s an initial notification point and then it escalates to the next support person after a defined period of time if the root cause is still outstanding. These notification groups are referenced when the script is called at the channel level.

    As a result of this we have many support notification groups covering a multitude of support scenarios across our complex environment; applications, platforms, OS types, SNMP etc as well as interacting with the broader business.

    Due to this complexity we often overlap notification groups, so if, for example, the space on the D: drive of an application server becomes critical we send the text alert to the service owners to action but also send advisory emails to the server support guys, we do this by referencing two different notification groups.

    Our main monitoring tool used to be HP OM and it could handle this side of things fantastically well with full visibility of each step in the alert/notification chain, SCOM much less so and as a result we’re still evolving in that space. Hope that makes sense? To this end being able to reference multiple subscribers/channels (Notification groups) within a Subscription would be very helpful. We would then populate the custom fields with the names of the notification groups and the 3rd part app reference ID therefore providing full bi-directional visibility and traceability. Thanks for reading 🙂

  37. Hi Tao,

    We are using scom 2012 R2 , im following you script for mail body notifications .
    While confiring time we getting this “””

    Error occurred when excuting C:\Scripts\SCOMEnhancedEmailNotification.ps1 located at AEADVCOM01.adced.int for alert ID .

    Alert Resolution State:

    **Note:Error will occur if the script tries to process an alert with Resolution State other than New.

    You cannot call a method on a null-valued expression. You cannot call a method on a null-valued expression. You cannot call a method on a null-valued expression. You cannot call a method on a null-valued expression. You cannot call a method on a null-valued expression. You cannot call a method on a null-valued expression. You cannot call a method on a null-valued expression. Cannot bind parameter ‘Id’. Cannot convert value “” to type “System.Guid”. Error: “Unrecognized Guid format.” Exception calling “Substring” with “2” argument(s): “StartIndex cannot be less than zero. Parameter name: startIndex” Exception calling “Substring” with “2” argument(s): “Index and length must refer to a location within the string. Parameter name: length”

    **Use below command to view the full details of this alert in SCOM Powershell console:

    get-alert -Id “” | format-list *

    SCOM link: http://AEADVCOM01/OperationsManager?DisplayMode=Pivot&AlertID=%7b%7d
    “”””

    2)we are not getting any notification via email.

    1. hallo
      i get errore :

      Exception calling “Send” with “1” argument(s): “A recipient must be specified.”
      At D:\Scripts\SCOMEnhancedEmailNotification.ps1:425 char:1
      + $SMTPClient.Send($MailMessage)
      + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
      + FullyQualifiedErrorId : InvalidOperationException

      Remove-Variable : Cannot find a variable with the name ‘to’.
      At D:\Scripts\SCOMEnhancedEmailNotification.ps1:415 char:3
      + Remove-Variable to
      + ~~~~~~~~~~~~~~~~~~
      + CategoryInfo : ObjectNotFound: (to:String) [Remove-Variable], I
      temNotFoundException
      + FullyQualifiedErrorId : VariableNotFound,Microsoft.PowerShell.Commands.R
      emoveVariableCommand

      Exception calling “Add” with “1” argument(s): “Value cannot be null.
      Parameter name: item”
      At D:\Scripts\SCOMEnhancedEmailNotification.ps1:414 char:3
      + $MailMessage.To.add($to)
      + ~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
      + FullyQualifiedErrorId : ArgumentNullException

      New-Object : Exception calling “.ctor” with “2” argument(s): “The parameter
      ‘address’ cannot be an empty string.
      Parameter name: address”
      At D:\Scripts\SCOMEnhancedEmailNotification.ps1:413 char:9
      + $to = New-Object System.Net.Mail.MailAddress($item.email, $item.name)
      + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo : InvalidOperation: (:) [New-Object], MethodInvoca
      tionException
      + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.Power
      Shell.Commands.NewObjectCommand

Leave a Reply

%d bloggers like this: