Welcome guest. Before posting on our computer help forum, you must register. Click here it's easy and free.

Author Topic: help - batch file to send automated email when windows service stops  (Read 30980 times)

0 Members and 1 Guest are viewing this topic.

29april

    Topic Starter


    Greenhorn

    hi, I need to create a batch file that sends an email automatically when a windows service stops.

    I could have the batch file run every 10 minutes to see if the service is active, but I have no idea how to give an if condition and then send an email. First of all is this possible? any suggestions would be great to know. Thanks.

    Helpmeh



      Guru

    • Roar.
    • Thanked: 123
      • Yes
      • Yes
    • Computer: Specs
    • Experience: Familiar
    • OS: Windows 8
    Re: help - batch file to send automated email when windows service stops
    « Reply #1 on: December 04, 2009, 03:15:01 PM »
    Well you can't send emails with batch, and I don't have much experience with windows services, so I suggest using another language maybe.
    Where's MagicSpeed?
    Quote from: 'matt'
    He's playing a game called IRL. Great graphics, *censored* gameplay.

    gh0std0g74



      Apprentice

      Thanked: 37
      Re: help - batch file to send automated email when windows service stops
      « Reply #2 on: December 04, 2009, 04:37:35 PM »
      hi, I need to create a batch file that sends an email automatically when a windows service stops.

      I could have the batch file run every 10 minutes to see if the service is active, but I have no idea how to give an if condition and then send an email. First of all is this possible? any suggestions would be great to know. Thanks.

      here's an example vbscript to check service is up
      Code: [Select]
      strComputer = "."
      Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
      Set colRunningServices = objWMIService.ExecQuery("Select * from Win32_Service")
      For Each objService in colRunningServices
          If objService.DisplayName = "Print Spooler" And objService.State = "Running" Then
          WScript.Echo "Print Spooler is Running"
              'SEnd email here.
          End If
      Next
      for sending email, you can either do it with vbscript (search google for "vbscript email") and there are code examples to do that. OR you can use blat.exe (search google for download). For batch method, you can use sc. check sc /?  for more.

      gh0std0g74



        Apprentice

        Thanked: 37
        Re: help - batch file to send automated email when windows service stops
        « Reply #3 on: December 04, 2009, 04:38:55 PM »
        Well you can't send emails with batch,
        yes you can.

        Helpmeh



          Guru

        • Roar.
        • Thanked: 123
          • Yes
          • Yes
        • Computer: Specs
        • Experience: Familiar
        • OS: Windows 8
        Re: help - batch file to send automated email when windows service stops
        « Reply #4 on: December 04, 2009, 04:53:55 PM »
        yes you can.
        I mean without downloading 3rd party programs. Anything that has a command-line opyion can be run with batch.
        Where's MagicSpeed?
        Quote from: 'matt'
        He's playing a game called IRL. Great graphics, *censored* gameplay.

        29april

          Topic Starter


          Greenhorn

          Re: help - batch file to send automated email when windows service stops
          « Reply #5 on: December 04, 2009, 04:54:42 PM »
          gh0std0g74,

          Thanks I'll search for sample VB scripts to send email as well. but how do I call this VB script from a batch file? Please let me know, I think that would solve my problem :)

          29april

            Topic Starter


            Greenhorn

            Re: help - batch file to send automated email when windows service stops
            « Reply #6 on: December 04, 2009, 05:03:11 PM »
            Also, is there a way for batch file to do it independently (without use of VB scripts)? Installing VB might be a long process

            Helpmeh



              Guru

            • Roar.
            • Thanked: 123
              • Yes
              • Yes
            • Computer: Specs
            • Experience: Familiar
            • OS: Windows 8
            Re: help - batch file to send automated email when windows service stops
            « Reply #7 on: December 04, 2009, 05:31:37 PM »
            You already have it installed. There is a cscript program that lets you run vbs files.
            Where's MagicSpeed?
            Quote from: 'matt'
            He's playing a game called IRL. Great graphics, *censored* gameplay.

            29april

              Topic Starter


              Greenhorn

              Re: help - batch file to send automated email when windows service stops
              « Reply #8 on: December 04, 2009, 06:00:47 PM »
              Thanks Helpmeh, can u let me know the code u use in batch file to call the vb script?

              Geek-9pm


                Mastermind
              • Geek After Dark
              • Thanked: 1026
                • Gekk9pm bnlog
              • Certifications: List
              • Computer: Specs
              • Experience: Expert
              • OS: Windows 10
              Re: help - batch file to send automated email when windows service stops
              « Reply #9 on: December 04, 2009, 06:17:22 PM »
              Some reading to do.  8)
              Quote
              Visual Basic Scripting Edition
              VBScript User's Guide
              The VBScript User's Guide includes the following sections which explain the concept of Visual Basic Scripting Edition (VBScript) and how to use it.
              http://msdn.microsoft.com/en-us/library/sx7b3k7y(VS.85).aspx

              gh0std0g74



                Apprentice

                Thanked: 37
                Re: help - batch file to send automated email when windows service stops
                « Reply #10 on: December 04, 2009, 07:38:31 PM »
                gh0std0g74,

                Thanks I'll search for sample VB scripts to send email as well. but how do I call this VB script from a batch file? Please let me know, I think that would solve my problem :)

                Code: [Select]
                c:\test > cscript /nologo myscript.vbs

                Salmon Trout

                • Guest
                Re: help - batch file to send automated email when windows service stops
                « Reply #11 on: December 05, 2009, 01:46:28 AM »
                Quote
                c:\test > cscript /nologo myscript.vbs

                //nologo with 2 slashes is preferred


                29april

                  Topic Starter


                  Greenhorn

                  Re: help - batch file to send automated email when windows service stops
                  « Reply #12 on: December 05, 2009, 02:16:00 AM »
                  thanks for your superb support, people.. Im not done yet but I guess I got all what I wanted to know :-)

                  Salmon Trout

                  • Guest
                  Re: help - batch file to send automated email when windows service stops
                  « Reply #13 on: December 05, 2009, 02:44:51 AM »
                  Used without parameters, NET START returns a list of services.

                  Code: [Select]
                  C:\>net start
                  These Windows services are started:

                     Application Layer Gateway Service
                     Avira AntiVir Scheduler
                     COM+ Event System
                     COM+ System Application
                     Computer Browser
                     Cryptographic Services
                     DCOM Server Process Launcher
                     DHCP Client
                     Distributed Link Tracking Client
                     DNS Client
                     Event Log
                     Fast User Switching Compatibility
                     Folder Size
                     Help and Support
                     IPSEC Services
                     Java Quick Starter
                     Logical Disk Manager
                     MS Software Shadow Copy Provider
                     Network Connections
                     Network Location Awareness (NLA)
                     Plug and Play
                     Print Spooler
                     Protected Storage
                     Rapport Management Service
                     Remote Procedure Call (RPC)
                     Remote Procedure Call (RPC) Locator
                     Remote Registry
                     Secondary Logon
                     Security Accounts Manager
                     Security Center
                     Server
                     Shell Hardware Detection
                     SSDP Discovery Service
                     System Event Notification
                     Task Scheduler
                     TCP/IP NetBIOS Helper
                     Terminal Services
                     Themes
                     VMware vCenter Converter Server
                     Volume Shadow Copy
                     WebClient
                     Windows Audio
                     Windows Firewall/Internet Connection Sharing (ICS)
                     Windows Image Acquisition (WIA)
                     Windows Management Instrumentation
                     Windows Time
                     Windows User Mode Driver Framework
                     Workstation

                  The command completed successfully.

                  In a batch you can use this with a pipe to FIND and the && (errorlevel=0) and  || (errorlevel > 0) operators to see if a service is running or is not running and do something in those situations
                  Code: [Select]
                  set ServiceName=Java Quick Starter

                  net start | FIND "%ServiceName%" && (
                      echo The %ServiceName% service is running"
                      REM other commands
                      REM other commands
                      REM etc
                      )

                  net start | FIND "%ServiceName%" || (
                      echo The %ServiceName% service is NOT running
                      REM other commands
                      REM other commands
                      REM etc
                      )

                  gh0std0g74



                    Apprentice

                    Thanked: 37
                    Re: help - batch file to send automated email when windows service stops
                    « Reply #14 on: December 05, 2009, 05:20:14 AM »
                    //nologo with 2 slashes is preferred


                    yes. I always put /nologo after cscript.exe and its ok that way.  Up to the individual until M$hit makes it mandatory for  double slash syntax once and for all.

                    Salmon Trout

                    • Guest
                    Re: help - batch file to send automated email when windows service stops
                    « Reply #15 on: December 05, 2009, 06:12:00 AM »
                    The official recommendation for the Windows scripting engine is to use double slashes for switches intended to be read by the engine (cscript.exe or wscript.exe) and single slashes for options intended to be read by the script.

                    I am indebted to my friend Dias de Verano for this explanation of the reason.

                    The help visible when you type wscript /? (or more properly wscript //?) at the prompt shows 2 slashes for the switches available, although one will work in a simple case where the script itself is not supplied with any slashed parameters, as you have noticed.

                    The scripting host programs cscript.exe and wscript.exe are written to interpret doubly slashed command line switches as intended for themselves. The official advice from Microsoft is to use two slashes // for options specific to the scripting hosts cscript.exe and wscript.exe so that the hosts can distinguish between switches meant for them and those which may be meant for the scripts which they are running.

                    You may not have realised that, because the vbs file extension is associated (by Windows) with wscript.exe, the following have identical effect both at the command line and in a batch:

                    Code: [Select]
                    wscript anyscript.vbs

                    anyscript.vbs

                    And so do these

                    Code: [Select]
                    wscript //nologo anyscript.vbs

                    anyscript.vbs //nologo

                    So if anyscript had a parameter /goose either of these following could be used. Without the double slash convention the second invocation format would be ambiguous: (as to which parameter was for cscript.exe and which one was for anyscript.vbs)

                    Code: [Select]
                    wscript //nologo anyscript.vbs /goose

                    anyscript.vbs //nologo /goose


                    Bukhari1986



                      Rookie

                      Thanked: 2
                      Re: help - batch file to send automated email when windows service stops
                      « Reply #16 on: December 05, 2009, 08:01:38 AM »
                      great salmon

                      I am impressed :D

                      Salmon Trout

                      • Guest
                      Re: help - batch file to send automated email when windows service stops
                      « Reply #17 on: December 05, 2009, 08:13:20 AM »
                      In addition to the above I point out that you can modify various script engine options:

                      you can set the default scripting engine to be either cscript or wscript

                      you can set the default logo behaviour to be //nologo or //logo

                      type either cscript //? or wscript //? at the prompt to see how.


                      Sidewinder



                        Guru

                        Thanked: 139
                      • Experience: Familiar
                      • OS: Windows 10
                      Re: help - batch file to send automated email when windows service stops
                      « Reply #18 on: December 05, 2009, 08:44:18 AM »
                      hi, I need to create a batch file that sends an email automatically when a windows service stops.

                      I could have the batch file run every 10 minutes to see if the service is active, but I have no idea how to give an if condition and then send an email. First of all is this possible? any suggestions would be great to know. Thanks.

                      Another way to approach this would be to monitor the service and send the email when the service status changes to stopped. Rather then manually run a batch file every 10 minutes or use the scheduler, this script will run in an infinite loop monitoring the service.

                      Code: [Select]
                      strComputer = "."
                      Set objWMIService = GetObject("winmgmts:" _
                          & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
                      Set colMonitoredProcesses = objWMIService. _
                          ExecNotificationQuery("Select * From __InstanceModificationEvent " _
                              & " Within 1 where TargetInstance ISA 'Win32_Service'")

                      Do While True
                        Set objLatestProcess = colMonitoredProcesses.NextEvent
                        If LCase(objLatestProcess.TargetInstance.Name) = "" Then    'Name of service quoted; do not use display name
                          If objLatestProcess.TargetInstance.State = "Stop pending" Then
                          Call SendMail
                          End if
                          If objLatestProcess.TargetInstance.State = "Stopped" Then
                          Call SendMail
                          End if
                        End if
                      Loop

                      Sub SendMail()
                      Set cdo = CreateObject("CDO.Message")
                      With cdo
                      .Subject = "Service Down" 'email subject line quoted
                      .From = "" 'your email address quoted
                      .To = "" 'recipient email address quoted
                      .TextBody = "" 'email body text quoted
                      .Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
                      .Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "" 'your ISP SMTP server address
                      .Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
                      .Configuration.Fields.Update
                      .Send
                      End With
                      Set cdo = Nothing
                      End Sub

                      Fill in the information where noted, save script with a VBS extension and run from the command prompt as cscript scriptname.vbs

                      Good luck.  8)
                      The true sign of intelligence is not knowledge but imagination.

                      -- Albert Einstein

                      Salmon Trout

                      • Guest
                      Re: help - batch file to send automated email when windows service stops
                      « Reply #19 on: December 05, 2009, 08:47:22 AM »
                      Sidewinder, once the script discovers the service is in the stopped state,  will it keep sending emails every 10 minutes?

                      Bukhari1986



                        Rookie

                        Thanked: 2
                        Re: help - batch file to send automated email when windows service stops
                        « Reply #20 on: December 05, 2009, 09:09:36 AM »
                        @ sidewinder

                        won't it require password for sending the mails

                        I mean if i add in the field From="[email protected]"

                        then will it send the email without the password here ??

                        Sidewinder



                          Guru

                          Thanked: 139
                        • Experience: Familiar
                        • OS: Windows 10
                        Re: help - batch file to send automated email when windows service stops
                        « Reply #21 on: December 05, 2009, 09:47:54 AM »
                        Sidewinder, once the script discovers the service is in the stopped state,  will it keep sending emails every 10 minutes?


                        No. The script only sends an email when an event changes the service state to stopped or stop pending. Apparently, services and processes act differently in that processes terminate and flush out of memory while services are forever and may simply stop running.

                        @ sidewinder

                        won't it require password for sending the mails

                        I mean if i add in the field From="[email protected]"

                        then will it send the email without the password here ??

                        Depends on the ISP. I got it to work as posted, but if a username and password are required (security breach)  there are CDO configuration items for just that purpose. The OP never even mentioned the service name and for all we know the email may be going through an internal network where username and password are not required.

                         8)
                        The true sign of intelligence is not knowledge but imagination.

                        -- Albert Einstein

                        Geek-9pm


                          Mastermind
                        • Geek After Dark
                        • Thanked: 1026
                          • Gekk9pm bnlog
                        • Certifications: List
                        • Computer: Specs
                        • Experience: Expert
                        • OS: Windows 10
                        Re: help - batch file to send automated email when windows service stops
                        « Reply #22 on: December 05, 2009, 11:58:06 AM »
                        The link below is old material. It dates back to Windows 98.
                        OLEXP: How to Send Outlook Express Mail from a Command Line

                        29april

                          Topic Starter


                          Greenhorn

                          Re: help - batch file to send automated email when windows service stops
                          « Reply #23 on: December 17, 2009, 12:39:53 PM »
                          I executed the below script but nothing happens.

                          If the service is stopped I get a dialog box with the wscript.echo command, if it is started, nothing happens. emails are not being sent out either (I am able to send independently from command prompt).

                          Is there a way I can spool on the entire script to a log file and find out what the issue is? do you guys see anything wrong with the below script? PLEASE let me know. Thanks for ur support.


                          strComputer = "."
                          Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer &

                          "\root\cimv2")
                          Set colRunningServices = objWMIService.ExecQuery("Select * from Win32_Service")
                          For Each objService in colRunningServices
                              If objService.DisplayName = "Licensing Service" And objService.State = "Stopped" Then
                                 WScript.Echo "Licensing Service is Stopped"
                                  Call SendMail
                              End If
                          Next

                          Sub SendMail()
                             Set cdo = CreateObject("CDO.Message")
                             With cdo
                                .Subject = "Service Down"         'email subject line quoted
                                .From = "[email protected]"         'your email address quoted
                                .To = "[email protected]"      'recipient email address quoted
                                .TextBody = "Test"                           

                             'email body text quoted
                                

                          .Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
                                

                          .Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "localhost"   

                                'localhost
                                

                          .Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
                                .Configuration.Fields.Update      
                                .Send
                             End With
                             Set cdo = Nothing
                          End Sub

                          Sidewinder



                            Guru

                            Thanked: 139
                          • Experience: Familiar
                          • OS: Windows 10
                          Re: help - batch file to send automated email when windows service stops
                          « Reply #24 on: December 18, 2009, 06:57:50 AM »
                          I couldn't see anything wrong, but I couldn't get it to run either, even with valid values. Question: why is the smtpserver set to localhost? Are you running your own mail server? or are you using an ISP?

                          Code: [Select]
                          strComputer = "."
                          Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
                          Set colRunningServices = objWMIService.ExecQuery("Select * from Win32_Service")
                          For Each objService in colRunningServices
                              If objService.DisplayName = "Licensing Service" And objService.State = "Stopped" Then
                                 WScript.Echo "Licensing Service is Stopped"
                                  Call SendMail
                              End If
                          Next

                          Sub SendMail()   
                            Set CDO = CreateObject("CDO.Message")
                            With cdo
                          .From = "[email protected]"
                          .To = "[email protected]"
                          .Subject = "Service Down"
                          .Textbody = "Test"
                          .Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
                          .Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp mail server"
                          .Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
                          ' .Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "userid"
                          ' .Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "password"
                          ' .Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
                          .Configuration.Fields.Update
                          .Send
                          End With
                          End Sub

                          If using an ISP, check with them for the smtp server name and the port to use (this information is probably on their website). If you need to use authentication, uncomment the three configuration statements and fill in the values appropriately. Yeah, I know having the userid and password in the script is a security breach, but that is whole other subject.

                          Good luck.  8)
                          The true sign of intelligence is not knowledge but imagination.

                          -- Albert Einstein

                          ghostdog74



                            Specialist

                            Thanked: 27
                            Re: help - batch file to send automated email when windows service stops
                            « Reply #25 on: December 18, 2009, 07:38:38 AM »
                            or maybe there's something wrong with the schema site from M$.