SCOM Enhanced Email Notification Script Version 2

Written by Tao Yang

Few years ago, I posted the SCOM Enhanced Email Notification Script in this blog and became well adopted by the community. Over the last week or so, I have spent most of my time at night re-writing this script and I have completed the new version (2.0) now.

There are few reasons why I have decided to rewrite this script:

  • Make it to work in SCOM 2012
  • To be able to include Company Knowledge articles in the email (someone asked me about this a long time ago)
  • Ability to use an external / public SMTP server (i.e. gmail) to send emails so I can decommission the Exchange server in my test lab. – since all I use this Exchange server for is to send out alert notifications and it can’t email out to the real world!
  • Improve the email HTML body layout.

So what’s changed?

  • Now the script uses SCOM SDK instead of SCOM PowerShell snap-in / module. And because of this, it works on both SCOM 2007 R2 and SCOM 2012. – so far, from my experience playing with the them, the SDK’s in SCOM 2007 and 2012 look pretty similar!
  • Also because of the use of SCOM SDK, I’m able to retrieve Company Knowledge articles.
  • In the original script, it would only retrieve knowledge articles when the language of the article is ENU (“en-US”). Therefore, any knowledge articles stored in other language packs (such as ENA) in the management pack would not be retrieved. The script now retrieve ALL knowledge articles AND ALL company knowledge articles and display ALL of them in the email (as shown in the sample below).
  • I have moved all the customisations out of the script itself to a config.xml to store customised settings. No need to modify the PS1 script anymore. Simply make necessary changes in the config.xml and place it to the same folder as the script.
  • When setting up a native SCOM SMTP notification channel, there are only 2 authentication methods you can choose from: Anonymous and Windows Integrated. This script can be configured to use a separate user name and password to authenticate to SMTP so external SMTP servers such as gmail can be used. This eliminates the needs of having to use Exchange server for mail relay.

image

  • In the original script, the alert resolution state is updated once the script has processed the alert. This feature can now be turned off. – Because we don’t always want to update the resolution state.
  • Additionally, I have made the email body look a bit tidier, the layout now looks more similar to the alert view in the SCOM consoles:

image

How to setup command subscription?

The command subscription setup is very similar to the previous version. However, for the new script, the web console link also needs to be passed into the script. I remove the section to generate web console link for the alert because the web console link can be passed into the script as a parameter natively by SCOM, why generate it again in the script when it’s already available natively?

Assuming the script is located on D:\Script folder of your RMS / MS. here’s how you set it up:

image

From zip file that you can download from the link at the end of this post, you’ll find these files:

image

It contains:

  • The version 2 of the SCOMEnhancedEmailNotification.ps1 script.
  • config.xml that you will need to modify to suit your needs
  • XML explaination.xlsx – explains each tag of the config.xml in details.
  • Command Channel Setup.txt – what to enter when setting up command channel. (assuming the script is located at D:\Script). you can simply change the location of the script and email addresses, then copy & paste each field.
  • XML Sample – contains 3 config.xml samples. one for each SMTP authentication method (Anonymous, Integrated and Credential).

The notifications subscriber and subscriptions are setup exactly the same way as the original version of the script. you can simply refer to the original blog post.

DOWNLOAD HERE.

83 comments on “SCOM Enhanced Email Notification Script Version 2

  1. NIce!

  2. Wow, wonderful job Tao. I can’t wait to give this a shot in the lab.

  3. Pingback: ENHANCED SCOM Alerts Notification Emails! | Tao Yang's System Management Blog

  4. Pingback: Enhanced Email Notification Script for SCOM 2012 | 独居Server Core

  5. why it is limited by sending 5 alert per minute

    I have lab it generates many alert about 30 alert per minute ,only 5 alert per minute are notified and other alert are ignored

    • Please check the following warning alert

      Alert Name: Operations Manager failed to start a process due to lack of resources
      Alert Resolution State: Notified
      Alert Description:
      The process could not be created because the maximum number of asynchronous responses (5) has already been reached, and it will be dropped. Command executed: “C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe” -Command “& ‘”D:\Scripts\SCOMEnhancedEmailNotification.ps1″‘” -alertID ‘{b2e2fbe1-e24d-4241-bc2e-65ca316b95a8}’ -Recipients @(‘LDC OPERATIONS;Ramy.Shaker@linkdatacenter.net’) Working Directory: D:\Scripts One or more workflows were affected by this. Workflow name: Subscriptiond04c470f_720b_4d4d_abb5_20fb4108d9b2 Instance name: Alert Notification Subscription Server Instance ID: {E07E3FAB-53BC-BC14-1634-5A6E949F9230} Management group: SCOMCFG
      Alert Rule Name:
      Alert on Dropped Batch Responses
      Alert Rule Description:
      The rule generates alerts when batch responses are dropped.

    • Are you using an external SMTP server? Could that be a network delay between RMS and SMTP? also check the command parameter string. I have seen this issue with the previous version. which I found the fix: http://blog.tyang.org/2012/01/29/command-line-parameters-for-scom-command-notification-channel/

  6. Great work Tao, you did a very nice job on this. Will test it as soon as possible.

  7. Pingback: SCOM Enhanced Email Notification Script Version 2 « MS Tech BLOG

  8. Hi Tao, excellent script! Its working really well for us. I notice though in testing that the agent name is not being displayed in the subject of the e-mail alerts. I had a quick look and should line 251 be $AlertSource instead of $strAgentName? seems to work fine when changed?

  9. Hi,

    Awesome script, im getting this error below. Can you please check and let me know. What im doing wrong?

    ==========================================

    You cannot call a method on a null-valued expression.
    At C:\SCOMEnhancedEmailNotification\SCOMEnhancedEmailNotification.ps1:193 char:
    43
    + $strTimeRaised = $localtimeraised.ToString <<<< ()
    + CategoryInfo : InvalidOperation: (ToString:String) [], RuntimeE
    xception
    + FullyQualifiedErrorId : InvokeMethodOnNull

    Multiple ambiguous overloads found for "GetMonitoringKnowledgeArticles" and the
    argument count: "1".
    At C:\SCOMEnhancedEmailNotification\SCOMEnhancedEmailNotification.ps1:191 char:
    69
    + $KnowledgeArticles = $ManagementGroup.GetMonitoringKnowledgeArticles <<<< ($r
    uleID)
    + CategoryInfo : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodCountCouldNotFindBest

    You cannot call a method on a null-valued expression.
    At C:\SCOMEnhancedEmailNotification\SCOMEnhancedEmailNotification.ps1:185 char:
    57
    + $monitoringObjectId = $alert.monitoringobjectID.tostring <<<< ()
    + CategoryInfo : InvalidOperation: (tostring:String) [], RuntimeE
    xception
    + FullyQualifiedErrorId : InvokeMethodOnNull

    You cannot call a method on a null-valued expression.
    At C:\SCOMEnhancedEmailNotification\SCOMEnhancedEmailNotification.ps1:173 char:
    22
    + if ($severity.ToLower <<<< () -eq "error")
    + CategoryInfo : InvalidOperation: (ToLower:String) [], RuntimeEx
    ception

    • Need more info. How did you call the script?

      • Hi,

        Thanks for the reply, i right clicked on the script ran is via powershell…Also, it doesnt seem to be running via SCOM.

        im using the updated command line. Do i need to include email addresses in the command line? or is it enough if i update them in subcribers?

        Also, the Alerts that im testing them with are custom monitors i created to run SQL scripts.I hope that will make no difference.

        Thanks!
        Ismail

        • you can’t run it by right click, you need to pass the parameters. you can’t use normal SMTP subscribers. you will need to pass the emails into the script.

          • Yes, that is what im doing. I passed the emails in the parameters. Below is the command line im using.

            -Command “& ‘”D:\Scripts\SCOMEnhancedEmailNotification.ps1″‘” -alertID ‘$Data/Context/DataItem/AlertId$’ -Recipients @(‘Tao Yang;Tao.Yang@xxxx.com’,John Smith;John.Smith@xxxx.com‘)

            i have changed the path of the file location to suit my needs..rest all is same.

            Can you please help me on this. I’m using an externally hosted exchange. I updated the config.xml to send error logs to a specific email address. It does so, the emails are going for the errors only, that too when i run the script as i stated.

            Please let me know, what changes i need to make to ensure the script runs via SCOM. Im using SCOM 2012.

            Thanks,
            Ismail

          • please take a look at the Command Channel Setup.txt that comes from the zip file from this post. your parameters are wrong.

  10. Just what I was looking for.

  11. Pingback: Bug Fixes for SCOM Enhanced Email Notification Script V2 | Tao Yang's System Management Blog

  12. I’ve just updated this script and associated instruction to address 2 bugs. the download link on this blog post has been updated.

    • Hi Tao,

      Its working now, thanks a ton for the wonderful script. Sorry for bothering you with my questions.

      Cheers Mate!

      • Hi Ismail,

        How did you solved it? May you please share the steps with me, I’m also having the same problem in my SCOM 2012 Infra.
        Thanks.

        • Hi Bob,

          Are you getting error emails?? When you run the PS script, i see above you ran it manually.

          If you are getting those emails, then you need to look at your subscriptions.

          Please note those have to be Command channel subscribers not SMTP. That is how i got it fixed.

          TAO: I hope you don’t mind me replying here..Just trying to help.

  13. Hi Tao

    Thanks for your script. Unfortunately I always get this error:
    “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. You cannot call a method on a null-valued expression. Exception calling “.ctor” with “1″ argument(s): “The user XXX\User does not have sufficient permission to perform the operation.”

    The user is my default action account. Which permission is missing?

    Thx
    Stefan

    • Hi Stefan,
      How are you trying to run the script? from Powershell prompt or via command channel subscription. also, could you please provide the full argument you’ve passed into the script?

      Regards
      Tao

      • Hi Tao,

        Can you help me disable the email alerts for notified. Im getting two emails per alert. I just need one.

        Thanks,
        Ismail

        • Do you mean you don’t want the script to change your alert resolution state? please take a look at the “XML explaination.xlsx” spreadsheet. you can do so by changing the value in XML to -1.

      • Hi Tao

        I run the script via channel subscription.

        Thats my command line:
        -Command “& ‘”D:\OpsMgr\Scripts\Send-Notification.50\SCOMEnhancedEmailNotification.ps1″‘” -alertID ‘$Data/Context/DataItem/AlertId$’ -WebConsoleLink ‘”$Target/Property[Type="Notification!Microsoft.SystemCenter.AlertNotificationSubscriptionServer"]/WebConsoleUrl$?DisplayMode=Pivot&AlertID=$Data/Context/DataItem/AlertId$”‘ -Recipients @(‘Stefan Haefliger;stefan.haefliger@example.com,’Stefan Econis;stefan.haefliger@otherexample.com’)

        • Hi Stefan,

          Your command channel looks OK. how about manually running the script? you’ll need to replace the alertID with a real alert ID and just put a dummy URL in (i.e. http://google.com).

          • Hi Thao

            Changed my commandline to:
            -Command “& ‘”D:\OpsMgr\Scripts\Send-Notification.50\SCOMEnhancedEmailNotification.ps1″‘” -alertID ’0′ -WebConsoleLink ‘”http://google.com”‘ -Recipients @(‘Stefan Haefliger;stefan.haefliger@example.com’,’Stefan Haefliger ;stefan.haefliger@otherexample.com’)

            Unfortunttly I still get an error..

            Here my error log:
            You cannot call a method on a null-valued expression.
            At D:\OpsMgr\Scripts\Send-Notification.50\SCOMEnhancedEmailNotification.ps1:1
            94 char:43
            + $strTimeRaised = $localtimeraised.ToString <<<< ()
            + CategoryInfo : InvalidOperation: (ToString:String) [], RuntimeE
            xception
            + FullyQualifiedErrorId : InvokeMethodOnNull

            You cannot call a method on a null-valued expression.
            At D:\OpsMgr\Scripts\Send-Notification.50\SCOMEnhancedEmailNotification.ps1:1
            92 char:69
            + $KnowledgeArticles = $ManagementGroup.GetMonitoringKnowledgeArticles <<<< ($r
            uleID)
            + CategoryInfo : InvalidOperation: (GetMonitoringKnowledgeArticle
            s:String) [], RuntimeException
            + FullyQualifiedErrorId : InvokeMethodOnNull

            You cannot call a method on a null-valued expression.
            At D:\OpsMgr\Scripts\Send-Notification.50\SCOMEnhancedEmailNotification.ps1:1
            86 char:57
            + $monitoringObjectId = $alert.monitoringobjectID.tostring <<<< ()
            + CategoryInfo : InvalidOperation: (tostring:String) [], RuntimeE
            xception
            + FullyQualifiedErrorId : InvokeMethodOnNull

            You cannot call a method on a null-valued expression.
            At D:\OpsMgr\Scripts\Send-Notification.50\SCOMEnhancedEmailNotification.ps1:1
            74 char:22
            + if ($severity.ToLower <<<< () -eq "error")
            + CategoryInfo : InvalidOperation: (ToLower:String) [], RuntimeEx
            ception
            + FullyQualifiedErrorId : InvokeMethodOnNull

            You cannot call a method on a null-valued expression.
            At D:\OpsMgr\Scripts\Send-Notification.50\SCOMEnhancedEmailNotification.ps1:1
            72 char:37
            + $severity = $alert.Severity.ToString <<<< ()
            + CategoryInfo : InvalidOperation: (ToString:String) [], RuntimeE
            xception
            + FullyQualifiedErrorId : InvokeMethodOnNull

            You cannot call a method on a null-valued expression.
            At D:\OpsMgr\Scripts\Send-Notification.50\SCOMEnhancedEmailNotification.ps1:1
            71 char:51
            + $localtimeRaised = ($alert.timeraised).tolocaltime <<<< ()
            + CategoryInfo : InvalidOperation: (tolocaltime:String) [], Runti
            meException
            + FullyQualifiedErrorId : InvokeMethodOnNull

            You cannot call a method on a null-valued expression.
            At D:\OpsMgr\Scripts\Send-Notification.50\SCOMEnhancedEmailNotification.ps1:1
            68 char:56
            + $strResolutionState = ($alert.resolutionstate).ToString <<<< ()
            + CategoryInfo : InvalidOperation: (ToString:String) [], RuntimeE
            xception
            + FullyQualifiedErrorId : InvokeMethodOnNull

            You cannot call a method on a null-valued expression.
            At D:\OpsMgr\Scripts\Send-Notification.50\SCOMEnhancedEmailNotification.ps1:1
            64 char:47
            + $alert = ($ManagementGroup.GetMonitoringAlerts <<<< ($AlertCriteria))[0]
            + CategoryInfo : InvalidOperation: (GetMonitoringAlerts:String) [
            ], RuntimeException
            + FullyQualifiedErrorId : InvokeMethodOnNull

            New-Object : Exception calling ".ctor" with "1" argument(s): "The user AICORP\s
            a_scom_msaa does not have sufficient permission to perform the operation."
            At D:\OpsMgr\Scripts\Send-Notification.50\SCOMEnhancedEmailNotification.ps1:1
            44 char:30
            + $ManagementGroup = New-Object <<<< Microsoft.EnterpriseManagement.Management
            Group($MGConnSetting)
            + CategoryInfo : InvalidOperation: (:) [New-Object], MethodInvoca
            tionException
            + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.Power
            Shell.Commands.NewObjectCommand

          • 0 is not a valid alert ID. to test, use SCOM Powershell console to retrieve an open alert, copy the alert ID to the commandline where you run my script. Also, try to run the script manually from PowerShell command, make sure it works before using the command channel.

  14. Sorry my misunterstandig

    I did run your script directly via the Powershell command and get this ouput…

    PS D:\OpsMgr\Scripts\Send-Notification.50> .\SCOMEnhancedEmailNotification.ps1 -alertID ’4ba8ff85-87fd-e855-b4a4-7aac4
    f8b0bf5′ -WebConsoleLink ‘”http://google.com”‘ -Recipients @(‘Stefan Haefliger;stefan.haefliger@example.com’,’Stefan Haefliger
    ;stefan.haefliger@otherexample.ch’)
    You cannot call a method on a null-valued expression.
    At D:\OpsMgr\Scripts\Send-Notification.50\SCOMEnhancedEmailNotification.ps1:168 char:56
    + $strResolutionState = ($alert.resolutionstate).ToString <<<< ()
    + CategoryInfo : InvalidOperation: (ToString:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    You cannot call a method on a null-valued expression.
    At D:\OpsMgr\Scripts\Send-Notification.50\SCOMEnhancedEmailNotification.ps1:171 char:51
    + $localtimeRaised = ($alert.timeraised).tolocaltime <<<< ()
    + CategoryInfo : InvalidOperation: (tolocaltime:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    You cannot call a method on a null-valued expression.
    At D:\OpsMgr\Scripts\Send-Notification.50\SCOMEnhancedEmailNotification.ps1:172 char:37
    + $severity = $alert.Severity.ToString <<<< ()
    + CategoryInfo : InvalidOperation: (ToString:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    You cannot call a method on a null-valued expression.
    At D:\OpsMgr\Scripts\Send-Notification.50\SCOMEnhancedEmailNotification.ps1:174 char:22
    + if ($severity.ToLower <<<< () -eq "error")
    + CategoryInfo : InvalidOperation: (ToLower:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    You cannot call a method on a null-valued expression.
    At D:\OpsMgr\Scripts\Send-Notification.50\SCOMEnhancedEmailNotification.ps1:186 char:57
    + $monitoringObjectId = $alert.monitoringobjectID.tostring <<<< ()
    + CategoryInfo : InvalidOperation: (tostring:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    Multiple ambiguous overloads found for "GetMonitoringKnowledgeArticles" and the argument count: "1".
    At D:\OpsMgr\Scripts\Send-Notification.50\SCOMEnhancedEmailNotification.ps1:192 char:69
    + $KnowledgeArticles = $ManagementGroup.GetMonitoringKnowledgeArticles <<<< ($ruleID)
    + CategoryInfo : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodCountCouldNotFindBest

    You cannot call a method on a null-valued expression.
    At D:\OpsMgr\Scripts\Send-Notification.50\SCOMEnhancedEmailNotification.ps1:194 char:43
    + $strTimeRaised = $localtimeraised.ToString <<<< ()
    + CategoryInfo : InvalidOperation: (ToString:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    You cannot call a method on a null-valued expression. Multiple ambiguous overloads found for "GetMonitoringKnowledgeArti
    cles" and the argument count: "1". You cannot call a method on a null-valued expression. You cannot call a method on a n
    ull-valued expression. You cannot call a method on a null-valued expression. You cannot call a method on a null-valued e
    xpression. You cannot call a method on a null-valued expression.

    • Looks like the script can’t retrieve the alert. Could you run below lines from a PowerShell prompt on your RMS server and see if you can see the detail of that alert? (update the first line first)

      $alertID = “enter your alert ID here first”
      function Load-SDK()
      {
      [System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.EnterpriseManagement.OperationsManager.Common”) | Out-Null
      [System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.EnterpriseManagement.OperationsManager”) | Out-Null
      }
      Load-SDK

      $alertID = $alertID.toString()

      #remove “{” and “}” around the $alertID if exist
      if ($alertID.substring(0,1) -match “{“)
      {
      $alertID = $alertID.substring(1, ( $alertID.length -1 ))
      }
      if ($alertID.substring(($alertID.length -1), 1) -match “}”)
      {
      $alertID = $alertID.substring(0, ( $alertID.length -1 ))
      }
      $MGConnSetting = New-Object Microsoft.EnterpriseManagement.ManagementGroupConnectionSettings($Env:COMPUTERNAME)
      $ManagementGroup = New-Object Microsoft.EnterpriseManagement.ManagementGroup($MGConnSetting)
      $AlertSearchCriteria = “Id = '$alertID‘”
      $AlertCriteria = New-object Microsoft.EnterpriseManagement.Monitoring.MonitoringAlertCriteria($AlertSearchCriteria)
      $alert = ($ManagementGroup.GetMonitoringAlerts($AlertCriteria))[0]
      $alert | fl *

  15. Sorry for the late reply

    I packed your script in a ps1 file and did run it…

    I get this error message..

    New-Object : Exception calling “.ctor” with “1″ argument(s): “The criteria used for query has an invalid character or i
    nvalid keyword. The following parse error was returned: Parse error before ba8ff85″
    At D:\OpsMgr\Scripts\test.ps1:23 char:29
    + $AlertCriteria = New-object <<<< Microsoft.EnterpriseManagement.Monitoring.MonitoringAlertCriteria($AlertSearchCrit
    eria)
    + CategoryInfo : InvalidOperation: (:) [New-Object], MethodInvocationException
    + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand

    Multiple ambiguous overloads found for "GetMonitoringAlerts" and the argument count: "1".
    At D:\OpsMgr\Scripts\test.ps1:24 char:48
    + $alert = ($ManagementGroup.GetMonitoringAlerts <<<< ($AlertCriteria))[0]
    + CategoryInfo : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodCountCouldNotFindBest

    • can you email me the script you packed and the exact command line that you ran. also, please make sure you run this script on your RMS server with an account that has at least SCOM operators rights.

  16. Hello Tao Yang,

    I’m using SCOM 2012 it has got 2 MS, I configured your script in one of the MS but it seems to be having some problem i get below error and it’s not working at all.

    You cannot call a method on a null-valued expression.
    At C:\Scripts\SCOMEnhancedEmailNotification.ps1:194 char:43
    + $strTimeRaised = $localtimeraised.ToString <<<< ()
    + CategoryInfo : InvalidOperation: (ToString:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    Multiple ambiguous overloads found for "GetMonitoringKnowledgeArticles" and the argument count: "1".
    At C:\Scripts\SCOMEnhancedEmailNotification.ps1:192 char:69
    + $KnowledgeArticles = $ManagementGroup.GetMonitoringKnowledgeArticles <<<< ($ruleID)
    + CategoryInfo : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodCountCouldNotFindBest

    You cannot call a method on a null-valued expression.
    At C:\Scripts\SCOMEnhancedEmailNotification.ps1:186 char:57
    + $monitoringObjectId = $alert.monitoringobjectID.tostring <<<< ()
    + CategoryInfo : InvalidOperation: (tostring:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    You cannot call a method on a null-valued expression.
    At C:\Scripts\SCOMEnhancedEmailNotification.ps1:174 char:22
    + if ($severity.ToLower <<<< () -eq "error")
    + CategoryInfo : InvalidOperation: (ToLower:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    You cannot call a method on a null-valued expression.
    At C:\Scripts\SCOMEnhancedEmailNotification.ps1:172 char:37
    + $severity = $alert.Severity.ToString <<<< ()
    + CategoryInfo : InvalidOperation: (ToString:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    You cannot call a method on a null-valued expression.
    At C:\Scripts\SCOMEnhancedEmailNotification.ps1:171 char:51
    + $localtimeRaised = ($alert.timeraised).tolocaltime <<<< ()
    + CategoryInfo : InvalidOperation: (tolocaltime:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    You cannot call a method on a null-valued expression.
    At C:\Scripts\SCOMEnhancedEmailNotification.ps1:168 char:56
    + $strResolutionState = ($alert.resolutionstate).ToString <<<< ()
    + CategoryInfo : InvalidOperation: (ToString:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    Exception calling "GetMonitoringAlerts" with "1" argument(s): "Id='' — Guid should contain 32 digits with 4 dashes (xx
    xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)."
    At C:\Scripts\SCOMEnhancedEmailNotification.ps1:164 char:47
    + $alert = ($ManagementGroup.GetMonitoringAlerts <<<< ($AlertCriteria))[0]
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

    You cannot call a method on a null-valued expression.
    At C:\Scripts\SCOMEnhancedEmailNotification.ps1:154 char:31
    + $strEmail = ($Recipient.split <<<< (";"))[1]
    + CategoryInfo : InvalidOperation: (split:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    You cannot call a method on a null-valued expression.
    At C:\Scripts\SCOMEnhancedEmailNotification.ps1:153 char:39
    + $strRecipientName = ($Recipient.split <<<< (";"))[0]
    + CategoryInfo : InvalidOperation: (split:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    Exception calling "Substring" with "2" argument(s): "StartIndex cannot be less than zero.
    Parameter name: startIndex"
    At C:\Scripts\SCOMEnhancedEmailNotification.ps1:134 char:23
    + if ($alertID.substring <<<< (($alertID.length -1), 1) -match "}")
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

    Exception calling "Substring" with "2" argument(s): "Index and length must refer to a location within the string.
    Parameter name: length"
    At C:\Scripts\SCOMEnhancedEmailNotification.ps1:130 char:23
    + if ($alertID.substring <<<< (0,1) -match "{")
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

  17. Here is the channel created:

    C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
    -Command “& ‘”C:\Scripts\SCOMEnhancedEmailNotification.ps1″‘” -alertID ‘$Data/Context/DataItem/AlertId$’ -WebConsoleLink ‘”$Target/Property[Type="Notification!Microsoft.SystemCenter.AlertNotificationSubscriptionServer"]/WebConsoleUrl$?DisplayMode=Pivot&AlertID=$Data/Context/DataItem/AlertId$”‘ -Recipients @(‘Bob_r;br@xxx.net.uk’)

    C:\Scripts

  18. Do I have to create a Run as account and profiles also? I’m getting the script error e-mails to my mail ID but not for the alerts which comes in SCOM Console :( alerts are not even turning from new to notified. Need your immediate assistance please. Thanks in advance.

  19. Working great, thanks Tao awesome Script, I just had to place the script on both the MS.

  20. “In the original script, it would only retrieve knowledge articles when the language of the article is ENU (“en-US”). Therefore, any knowledge articles stored in other language packs (such as ENA) in the management pack would not be retrieved. The script now retrieve ALL knowledge articles AND ALL company knowledge articles and display ALL of them in the email (as shown in the sample below)”.

    What if I only want the Knowledge article in ENU (“en-US”)no other language? where do I cange this? I i’m flooded with hell lot of knowledge articles in diffrent-2 language in notification e-mail. Specially with respect to Citrix alerts.

    • It’s by design. I didn’t code the script a way to be able to select language pack. why would Citrix MP have ENA language pack? are you talking about your unsealed MP for your company knowledge?

  21. Tao. First off, great script, thank you. I’m troubleshooting the execution and am fairly sure it is a rights issue; however, I’m not getting anything to come across via email. I’ve setup ProcMon to monitor activity individually on the SDK service host, powershell path and the script name itself but no activity comes through. I’ve looked for errors in the Powershell operational log with no errors. I’ve stepped through stripping the complete command from the SCOM command channel created and ran it successfully. The complete command is as follows (with ID and sensitive info stripped of course):

    C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Command “& ‘”E:\Library\Tools\SCOM2012_Tools\EnhancedEmail\SCOMEnhancedEmailNotification.ps1″‘” -alertID ‘[alert GUID]‘ -WebConsoleLink ‘”https://[scom fqdn]/OperationsManager?DisplayMode=Pivot&AlertID=[alert GUID]“‘ -Recipients @(‘[email pretty name];[email address]‘)

    I checked the SCOM admins user role and the group containing the server and client AA is in there. The server and client AA also has rights to the target folder containing the PS1. Any idea on what the owning process is executing the command channel in order that I can monitor for execution state and rights issues? Thanks for taking the time to create this script as well as the time to answer questions for those of us having issues.

    • Have you checked your PowerShell execution policy? try to set it to Unrestricted and see if you can run it.

      • Sorry, yes, it is set to Unrestricted.

        • what happens if you manually run the script? you’ll need to pass all required parameters in (For alert ID, just use the native SCOM PS snapin / module to get a new alert, copy the alert ID and paste into the command line).

          • The command line is in my first post. It works fine. See above for the parms passed in the script. Thanks again.

          • What if you manually run the script using the action account? btw, how did you configure the xml file? does your mail server require authentication or a valid return address etc.?

  22. If I run the complete command line using the Server Action Account the command runs successfully. I have the xml configured to connect to the SMTP server anonymously. I receive the alert email when run manually, but not through the OM 2012 Notification Channel structure.
    If I remember right it does require a valid return address with a certain domain. If the command runs successfully using the Server Action Account, then isn’t essentially the Notification Channel method we need to be looking into?

    • Could you email me screenshots of your command channel, subscriber and subscription?

      • Tao, the issue was creating a duplicate path on the 2nd MS in the MS group. I had only created the files/folder on one MS in the group. Once I created the supporting file structure on the second MS, then everything started kicking off. Now am running into the async response issue for command notification, but am implementing the global async reg key:

        HKEY_LOCAL_MACHINE\Software\Microsoft\Microsoft Operations Manager\3.0\Modules\Global\Command Executer\AsyncProcessLimit REG_DWORD:0x0000000a

        to increase from the global default 5 to 10. Thanks again for taking the time to look through my configuration.

  23. Thanks Tao,

    Would the following be possible in v3?

    1) Some way of making it easy to establish which alerts have been forwarded to email from the Monitoring view?

    2) For alerts that need to be manually closed, have the ability to deselect email notifications when these are Closed?

    I know, pie in the sky but no harm in asking :-)

    Cheers!

    • Hi David,

      Thanks for the suggestions. Currently, the script can be configured to update the resolution state once it has processed an alert (via XML), will that satisfy your needs? And when you setup your subscription, if you are only subscribing to new alerts, you won’t be notified when an alert is closed.

      Cheers
      Tao

  24. This is very useful ! Can you just please hint out how we can change the Color of the text or do BOLD ?

    Thanks alot for sharing !

    • the body of the email is HTML, so you can customize it by editing the relevant HTML tags for the email body in the script ($strBody) variable in the script.

      • Thanks alot, another thing is that im not receiving emails for any alert that got closed ? any ideas

        thanks alot in advance

      • Im receiving closed alert with SMTP but when i ise the ppwershell it doesnt notify on closed alerts and im using same
        criterias

        • solved it, there was an if statement to exit if the id is 255 , removed that and now its notifying on closing.

          thanks for the amazing script

          • It’s been so long I can’t even remember what’s included in the script. lol. if people need to use this notification for closed alerts, I think might be a good idea to include alert history in the email as well. I’ll try to update it when I have some spare time.

          • Hi dear Tao, Thanks in advance for your Script.
            would you please complete “Closed” part of this script. we need to have this part too.

  25. Is it possible to modify the script to enable the correlation of the Closed (255) events with the original alerts? It would be great to be able to suppress the Closed alerts if the original issue is resolved within the “Delay sending notifications if conditions remain unchanged for longer than” timeframe in the subscriptions. Or does anyone know a way of doing this?

  26. Knowledge Articles are great in notifications. But sometimes they have hyperlinks to external resources or to perfomance views/dashboards/etc…. Is it possible to save URLs in knowledge articles? Links appear as plain text in notifications. Thanks for the really amazing script.

  27. Tao – I have multiple subscribers that have groups of servers they manage – does this mean for the command line:

    Command line parameters:
    -Command “& ‘”D:\Scripts\SCOMEnhancedEmailNotification.ps1″‘” -alertID ‘$Data/Context/DataItem/AlertId$’ -WebConsoleLink ‘”$Target/Property[Type="Notification!Microsoft.SystemCenter.AlertNotificationSubscriptionServer"]/WebConsoleUrl$?DisplayMode=Pivot&AlertID=$Data/Context/DataItem/AlertId$”‘ -Recipients @(‘Your Name1;your.email1@domain.com’,’Your Name2;your.email2@domain.com’)

    Would i have to enter all of their names into this recipients section?

    • that’s correct. or you can create a distribution list in your email system so the recipients can be managed outside of SCOM.

      • Ok i think what i’m getting at is i’ll need to create separate cmd channels for each individual instead of making one long one in the parameter, each person has their own group of server’s they monitor so if i just add them all they get ALL the servers not just the ones in their group. I hope i’m understanding that right.

  28. Pingback: PowerShell and Tables | rambling cookie monster

  29. Hi i used you script but after I installed powershell 3.0 it stoped working. I didnt know why. after I run script end debug there is one small error that stope script to be executed. It is on line 252
    $strSubject = “SCOM $severity Alert on $AlertSource: $strAlertName”
    After $AlertSource it should be space and then :
    I checked in you original file and it is writen like that. you need to change this in download so that people doesnt have problems like I.
    If it is another issue I am not aware please reply

    • try add “-version 2″ switch at the beginning of the command line parameter field. would that work? This will force PowerShell to launch under version 2.0.

      • I run on some another issue in subscription in scom. It works again i think but we will see tomorow. Only thing I changed was installation of ps3 that I needed for one MP. Maybe I am chasing ghosts. :-)

  30. Pingback: SCOM 2012: Overview link blog - SysManBlog

  31. Hi Tao,
    I’m trying to use your script to allow my engineers to manually send an email to another system. I’ve tested it as per the above instructions which works automatically.
    I’m now creating a task to run the script manually rather than doing it via the subscription but when I try to create the task using the same command as the subscription I get this message.
    : Processing the template failed. See inner exception for details.
    Verification failed with [1] errors:
    ——————————————————-
    Error 1:
    : Failed to verify Console Task with ID: ConsoleTaskGeneratedByUIf9be32736c5c4ad68f84f19b7309da61
    Failed to verify value specified in [Parameter] tag: -Command “& ‘”C:\Scripts\email\SCOMEnhancedEmailNotification.ps1″‘” -alertID ‘$Data/Context/DataItem/AlertId$’ -WebConsoleLink ‘”$Target/Property[Type="Notification!Microsoft.SystemCenter.AlertNotificationSubscriptionServer"]/WebConsoleUrl$?DisplayMode=Pivot&AlertID=$Data/Context/DataItem/AlertId$”‘ -Recipients @(‘bob;bob@email.com’)Cannot resolve identifier [Notification!Microsoft.SystemCenter.AlertNotificationSubscriptionServer] in the context of ManagementPack [Management.Pack]. Unknown alias [Notification]

    Any help greatly appreciated
    Tim

    • after trying this methods again im not able set my default SMTp setting .
      any one pls guide me how to resolve this issue

  32. Hi Tao,

    I am using SCOM 2012 and has two management servers, i have copied the script in both the servers. Created subscription but i am not receiving any email alerts. If i try to run the script through powershell manually i am receiving errors.

    Exception calling “Substring” with “2″ argument(s): “Index and length must refer to a location within the string.
    Parameter name: length”
    At E:\scripts\SCOMEnhancedEmailNotification.ps1:130 char:23
    + if ($alertID.substring <<<< (0,1) -match "{")
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

    Exception calling "Substring" with "2" argument(s): "StartIndex cannot be less than zero.
    Parameter name: startIndex"
    At E:\scripts\SCOMEnhancedEmailNotification.ps1:134 char:23
    + if ($alertID.substring <<<< (($alertID.length -1), 1) -match "}")
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

    New-Object : Exception calling ".ctor" with "1" argument(s): "The requested operation timed out."
    At E:\scripts\SCOMEnhancedEmailNotification.ps1:144 char:30
    + $ManagementGroup = New-Object <<<< Microsoft.EnterpriseManagement.ManagementGroup($MGConnSetting)
    + CategoryInfo : InvalidOperation: (:) [New-Object], MethodInvocationException
    + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand

    You cannot call a method on a null-valued expression.
    At E:\scripts\SCOMEnhancedEmailNotification.ps1:153 char:39
    + $strRecipientName = ($Recipient.split <<<< (";"))[0]
    + CategoryInfo : InvalidOperation: (split:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    You cannot call a method on a null-valued expression.
    At E:\scripts\SCOMEnhancedEmailNotification.ps1:154 char:31
    + $strEmail = ($Recipient.split <<<< (";"))[1]
    + CategoryInfo : InvalidOperation: (split:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    You cannot call a method on a null-valued expression.
    At E:\scripts\SCOMEnhancedEmailNotification.ps1:164 char:47
    + $alert = ($ManagementGroup.GetMonitoringAlerts <<<< ($AlertCriteria))[0]
    + CategoryInfo : InvalidOperation: (GetMonitoringAlerts:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    You cannot call a method on a null-valued expression.
    At E:\scripts\SCOMEnhancedEmailNotification.ps1:168 char:56
    + $strResolutionState = ($alert.resolutionstate).ToString <<<< ()
    + CategoryInfo : InvalidOperation: (ToString:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    You cannot call a method on a null-valued expression.
    At E:\scripts\SCOMEnhancedEmailNotification.ps1:171 char:51
    + $localtimeRaised = ($alert.timeraised).tolocaltime <<<< ()
    + CategoryInfo : InvalidOperation: (tolocaltime:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    You cannot call a method on a null-valued expression.
    At E:\scripts\SCOMEnhancedEmailNotification.ps1:172 char:37
    + $severity = $alert.Severity.ToString <<<< ()
    + CategoryInfo : InvalidOperation: (ToString:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    You cannot call a method on a null-valued expression.
    At E:\scripts\SCOMEnhancedEmailNotification.ps1:174 char:22
    + if ($severity.ToLower <<<< () -eq "error")
    + CategoryInfo : InvalidOperation: (ToLower:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    You cannot call a method on a null-valued expression.
    At E:\scripts\SCOMEnhancedEmailNotification.ps1:186 char:57
    + $monitoringObjectId = $alert.monitoringobjectID.tostring <<<< ()
    + CategoryInfo : InvalidOperation: (tostring:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    You cannot call a method on a null-valued expression.
    At E:\scripts\SCOMEnhancedEmailNotification.ps1:192 char:69
    + $KnowledgeArticles = $ManagementGroup.GetMonitoringKnowledgeArticles <<<< ($ruleID)
    + CategoryInfo : InvalidOperation: (GetMonitoringKnowledgeArticles:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    You cannot call a method on a null-valued expression.
    At E:\scripts\SCOMEnhancedEmailNotification.ps1:194 char:43
    + $strTimeRaised = $localtimeraised.ToString <<<< ()
    + CategoryInfo : InvalidOperation: (ToString:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    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. 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. Exception calling ".ctor" with "1" argument(s): "The requested operation timed out." 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 locati
    on within the string.

  33. Thank you very much, Thao !
    But can get ONLY Company Knowledge ?
    Can replace Company Knowledge and Product Knowledge ?

  34. Hi Thao,
    Great script and working flawlessly!
    Is there any way to update parameters to send email notifications on Warning and Critical healthstate? Meaning that if Warning alert is generated and then processed by your script can the channel process the same alert when in Critical state? Currently only 1 email notification is processed for the same alert whether it is in Warning or Critical state.

    Thanks for your help.

  35. This is a great script. It may be worth adding a line (and some pre-checks) for logging. Some companies like to be able to see who a notification was sent to when told “SCOM didn’t send me a notification. Tell me why.”

    I modified the script so a new log file each day in a $ScriptRoot\Logs\. directory

    “$(get-date -Format “yyyy-MM-dd hh:mm:ss”): $AlertName : $alertID : $PathName [$ToList]” | add-Content “$ScriptRoot\Logs\$(get-date -Format “yyyy-MM-dd”).log”

    It would be a handy feature. Perhaps a config item in your XML to enable logging and a retention days for the log files.

    Just a thought.

  36. Pingback: Using an External Knowledge Base for OpsMgr | Tao Yang's System Management Blog

  37. Pingback: SCOM Enhanced Email Notification Script Version 2.1 - System Center Operations Manager - Site Home - MSDN Blogs

Leave a Reply