WMI Scripts

WMI - Starting and Stopping Services

 Restart Service VBScript

This is the page where I show you how to create a Microsoft WMI script that starts or stops a Windows service on a remote computer. (Other pages deal with controlling process and programs). 

My WMI code employs Win32 Service commands to control the operating system and persuade it to stop or start a named service (Alerter). The benefit of learning this Win32 method is that you can adapt it to restart other Windows services, especially Exchange services.

Topics for Stopping and Restarting Services

 ♣

Key WMI words: Win32 Process

Scenario for Starting and Stopping Services

Let me begin with a reminder.  WMI and VBScripts just mimic what you could do manually.  Therefore, the advantage of a WMI script is that it saves time and gives you the power of controlling other computers from the comfort of your chair.  For example, here is a classic script to restart the remote registry service remotely.

Example 1 - WMI Script to List the Services Running on Computer

As promised, we are going to create a script to start or stop Windows services, but to begin with, I want to list merely the services.  (Alerter, Netlogon, Pop3Svc etc).  My reasoning is to build up gradually, and also to provide a script to help us troubleshoot.  For instance, the main WMI script may fail because we type in the wrong name for the service, by getting a list we can be sure to spell the name of the Windows service correctly.

Prerequisites

The Win32_Service Class works for most clients, XP, W2K, even NT 4.0 and Win 9x.

Instructions for Creating Your List Services WMI Script

  1. Copy and paste the example script below into notepad or a VBScript editor.
  2. Which machine on your network do you wish to check?  Change line 15:
    strComputer = "." means, local machine.
  3. Save the file with a .vbs extension, for example: Service.vbs 
  4. Double click Service.vbs and check the list of Services.  I know it's eccentric that you only get a list from 'N' to 'Z'.  However, there are two reasons for this, firstly a complete list of A-Z would go off screen, secondly, I will let you into a secret, I was troubleshooting the why pop3svc would not work.  The answer was that services are case sensitive, it should have been Pop3Svc not pop3svc.

WMI Script to List Services

' Service.vbs
' Sample script to List services N-Z
' www.computerperformance.co.uk/
' Author Guy Thomas http://computerperformance.co.uk/
' Version 1.5 December 2010
' -------------------------------------------------------'
Option Explicit
Dim objWMIService, objItem, objService, strServiceList
Dim colListOfServices, strComputer, strService

'On Error Resume Next

' ---------------------------------------------------------
' Pure WMI commands
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
Set colListOfServices = objWMIService.ExecQuery _
("Select * from Win32_Service ")

' WMI and VBScript loop
For Each objService in colListOfServices
If UCase(Left(objService.name,1)) >"N" then
strServiceList = strServiceList & vbCr & _
objService.name

End if
Next

WScript.Echo strServiceList

' End of Example WMI script to list services

Note: Scripting Win32_Service is easier with PowerShell

Guy Recommends: WMI Monitor and It's Free!Solarwinds Free WMI Monitor

Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft's operating systems.  Fortunately, SolarWinds have created a Free WMI Monitor so that you can discover these gems of performance information, and thus improve your scripts.

Take the guess work out of which WMI counters to use when scripting the operating system, Active Directory or Exchange Server. Give this WMI monitor a try - it's free.

Download your free copy of WMI Monitor

WMI Tutorial - Learning Points

From a WMI perspective

1) If you are experienced with WMI, then the two features concentrate on are, Win32_Service and objService.name.

2)  If you are new to WMI then you will soon appreciate that all WMI scripts begin by employing winmgmts to access the root of the CIM library :
Set objWMIService = GetObject("winmgmts:" & strComputer & "\root\cimv2")

2) WMI often requires security clearance in order to query the other machine's hardware, this is why we add :  & "{impersonationLevel=impersonate}!\\" _  

3) Set colComputer = objWMIService.ExecQuery _ is a standard WMI phrase to prepare for the WQL command:  Select * from Win32_Service
".  The part we are particularly interested in is _Service.  Win32 has dozens of properties, here we need to query not the process, but the Service component.

From a VBScript perspective

4) What makes scripting so powerful is the speed with which VBScript loops through an array of objects or properties, in this instance the code to look out for is: For Each....In... Next. 

5)  I am particularly proud of the this command:strServiceList = strServiceList & vbCr & objService.name.  In scripting terms it's primitive, almost a non-entity, but to me it makes the output easier to read.

6) The only property of objService that we are interested in is, .Name. However, we could have substituted other properties, for example .State or .Status.

7) As I discussed at the outset, I deliberately decided to only display a subset of all possible services, I chose to filter with the command, If UCase(Left(objService.name,1)) >"N" then...  Incidentally, there is hardly a script that cannot be fine-tuned with an, If ... Then.. End If. statement.

8)  You could take a different road and output the service information to a file.  VBScript has all the tools you need to create a file and write a service on each line.  In that example, you would not need the If..Then filter.

Guy Recommends:  A Free Trial of the Network Performance Monitor (NPM)Review of Orion NPM v10

SolarWinds' Network Performance Monitor will help you discover what's happening on your network.  This utility will also guide you through troubleshooting; the dashboard will indicate whether the root cause is a broken link, faulty equipment or resource overload.

Perhaps the NPM's best feature is the way it suggests solutions to network problems.  Its second best feature is the ability to monitor the health of individual VMware virtual machines.  If you are interested in troubleshooting, and creating network maps, then I recommend that you give this Network Performance Monitor a try.

Download your free trial of SolarWinds Network Performance Monitor.

Example 2 - WMI Script to Stop, then Start a Windows Service

Of all my WMI scripts, this Stop / Start service example benefits most from you tweaking various lines of code.  Let me explain my dilemma.  I wanted to show you how to both start and stop a service.  However, on a production script you may not want to restart the service; you may just want to either start, or stop the service; if so experiment by ' Rem out either objService.StartService() or objService.StopService().  Line 24 - 26.

To take another example of how to customize my script, Alerter is a boring, but safe service to experiment with, so why not substitute another service for Alerter?  However, be careful and remember to leave the machine as you found it.  Learn from my mistakes! I once stopped the TCP/IP NetBIOS helper services with disastrous consequences to the machines connectivity.

Prerequisites

Special note: Make sure that Alerter Service is set to Manual or Automatic.  Check with Services Administrative Tools as necessary.

The Win32_Service Class works for most clients, XP, W2K, even NT 4.0 and Win 9x.

Instructions for Creating Your Restart Service VBScript

  1. Copy and paste the example script below into notepad or a VBScript editor.
  2. Which machine on your network do you wish to check?  Change line 15:
    strComputer = "." means, local machine.
 

' VBScript Restart Service.vbs
' Sample script to Stop or Start a Service
' www.computerperformance.co.uk/
' Created by Guy Thomas December 2010 Version 2.4
' -------------------------------------------------------'
Option Explicit
Dim objWMIService, objItem, objService
Dim colListOfServices, strComputer, strService, intSleep
strComputer = "."
intSleep = 15000
WScript.Echo " Click OK, then wait " & intSleep & " milliseconds"

'On Error Resume Next
' NB strService is case sensitive.
strService = " 'Alerter' "
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
Set colListOfServices = objWMIService.ExecQuery _
("Select * from Win32_Service Where Name ="_
& strService & " ")
For Each objService in colListOfServices
objService.StopService()
WSCript.Sleep intSleep
objService.StartService()
Next
WScript.Echo "Your "& strService & " service has Started"
WScript.Quit
' End of Example WMI script to Start / Stop services

Note: Starting services is much easier in PowerShell

WMI Tutorial - Learning Points

From a WMI perspective

1)  As you get to know me, you will realize that I love variables.  This script gave me a real challenge, I wanted to introduce strService so that I could change easily from the boring Alerter to the more useful Pop3Svc, here is the difficulty,
("Select * from Win32_Service Where Name =" & strService & " ").  I solved the problem by precise positioning of the two sets of speech marks, moreover, when I declared strService, it required the syntax " 'Alerter' " and not plain " Alerter ".  Those were trivial points but they can drive you mad if you don't work with VBScript every day.

2) If you are going to adapt this for a production task, then you may need to remove either line 24 objService.StopService() or two lines further down, objService.StartService(). 

However, Efrain D. kindly wrote in and said that he wished to restart, in which case leave in both and possible increase sleep 15000 to 30000, each 1000 is represents a one second delay.

3) I almost forgot, you also need to change strComputer ="." to strComputer = "Victim2 or whichever machine you wish to control.

From a VBScript perspective

4)  As this is a test script, I introduced a delay with WScript.Sleep, the values are in mille seconds so 15000 are just 15 seconds.

5) Even though there is only one computer, the script still needs the loop: For Each....In... Next.  Believe me, I tried to simplify the script by removing the loop, but all I got was an object required error.

PowerShell Example : How to Restart a Service

The service which benefits most from Restart-Service is, "Spooler".  The reason being the printer gives more trouble than any other piece of hardware, and often restarting the Spooler cures the problem.  The inferior, but ruthless method of curing such printer jams is to reboot the computer.  When the the computer is also a fileserver, this technique is undesirable.

Production Script

All you really need is this simple command:

# PowerShell Restart-Service example
Restart-Service "Spooler"

Note 1: You can change "Spooler" to the name of another service.  To list services see PowerShell's Get-Service

Summary of VBScript to Start / Stop a Windows Service

This script gives the full flavour of what WMI can achieve.  It gives you control over a distant machine, and also gives you an insight into the possible services that you could start or stop.  There are plenty of VBScript challenges: For... Each ...In ... Next loops; filters with If..then ... End if.  I also have concrete examples of Win32 properties.  Master these and VBScript will restart your services.

See more VBScript service examples:

VBScript Listing Process   • VBscript Starting a Process   VBScript Restart Service

• VBscript Kill Process   • WMI Tutorial   • Win32_Process   • PowerShell Services

WMI Home   • WMI Win32   • VBScript Echo   • WMI VBScript  • Free WMI Monitor

 *


Custom Search

Site Home

Guy Recommends: WMI Monitor for PowershellSolarwinds WMI Monitor

Windows Management Instrumentation (WMI) is most useful for PowerShell scripting.

SolarWinds have produced this Free WMI Monitor to take the guess work out of which WMI counters to use for applications like Microsoft Active Directory, SQL or Exchange Server.

Download your free copy of WMI Monitor

Author: Guy Thomas Copyright © 1999-2014 Computer Performance LTD All rights reserved.

Please report a broken link, or an error to: