GuidesWindows Services Management With WMI (Part 3)

Windows Services Management With WMI (Part 3)

ServerWatch content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.




The third, and final, article in this series will examine methods that enable users to install and remove Windows services. Win32_Service class offers two methods, Create and Delete, that provide this functionality.

The third, and final, article in Marcin Policht’s ‘Windows Services Management With WMI’ series examines methods that enable users to install and remove Windows services. Win32_Service class offers two methods, Create and Delete, that provide this functionality.

The Create method of the Win32_Service class is used to install a Win32 application as a service. Note, however, that not every application can be run as a service. The application must be able to communicate properly with the Service Control Manager — the program that manages all Windows services. Without this communication, Service Control Manager will not be able to correctly evaluate the state of the service and control it in the intended manner.

Create method is essentially just an installer program for an application that satisfies Service Control Manager requirements. Its primary function is to create required entries in the HKLMSYSTEMCurrentControlSetServices area of the registry.

Create method takes a number of input parameters (the majority of which are identical to the ones described in Part 2 of this series, documenting Win32_Service Change method):

  • Name — Name of the service used by service Control Manager
  • DisplayName — Display name of the service
  • PathName — Fully qualified path to the executable that implements the service
  • ServiceType — Type of service, which can take one of the following values:
    • 1 — Kernel driver
    • 2 — File system driver
    • 4 — Adapter
    • 8 — Recognized driver
    • 16 — Own process
    • 32 — Share process
    • 256 – Interactive process
  • ErrorControl — The severity in which the failure of the service affects the operating system. It can take one of the following values:
    • 0 — Ignore
    • 1 — Normal, user is notified
    • 2 — Severe, system is restarted with the last known good configuration
    • 3 — Critical, system attempts to restart with last known good configuration; if this causes an error, the system halts
  • StartMode — Indicates the start mode of the service and takes on the following values:
    • Boot
    • System
    • Automatic
    • Manual
    • Disabled
  • DesktopInteract — True or False, depending on whether the service can communicate with windows on the desktop
  • StartName — The name of the account under which the service runs; the account can be specified in the format DomainUsername (for domain accounts) or .Username (for local computer accounts). On Windows XP systems in Active Directory environment, you can also use the UPN format (i.e., username@domainname).

    The determination of which account to use depends on service functionality and system security. Keep in mind that the Local System account has practically unlimited privileges to the local computer. While this level of privileges is sometimes required, you should use it only if absolutely necessary. Note also that, unlike in Windows NT 4.0 domains, a Local System account can be granted access to network resources. This is because the security token for the Local System account contains SID for the computer account (the one on which Local System account is defined). Thus, you can grant the Local System account rights to access other computers on the network by assigning appropriate permissions to the computer account.

    When using LocalSystem or NetworkService accounts, ensure that the password is set to an empty string:

    StartName = "LocalSystem"
    StartPassword = ""
    

    or

    StartName = "NT AUTHORITYNetworkService"
    StartPassword = ""
    
  • StartPassword — Password of the account specified in the StartName parameter
  • LoadOrderGroup — Group that the service is a member of; by grouping services together, you can control their startup sequence. This sequence can be determined by looking up its list in the HKEY_LOCAL_MACHINESystemCurrentControlSetControlServiceGroupOrder registry key.
  • LoadOrderGroupDependencies — Array containing a list of groups that contain services that must be started prior to the start of target service
  • ServiceDependencies — Array containing a list of services that must be started prior to the start of target service

As also explained in Part 2, when setting a domain or local user account as a service account, you must grant this account the right to log on as a service. (NetworkService is granted this right by default, while LocalSystem account has unrestricted access to all local system resources.) In Windows 2000 and later, this is controlled by Group Policy and can be set on either locally or through Active Directory (in the Computer Configuration, Windows Settings, Security Settings, Local Policies, User Rights Assignment node by modifying the value of Log on as a service entry).

The following script creates the automatically starting, non-critical service for an application called MyService.exe running under Local System account and interacting with the desktop. Within the script, other parameters (not used in the example), have been commented out.

sComputer 	= "REPLACE ME !!!!"	'replace with name of target computer
sStartMode	= "Automatic"
StartName 	= "LocalSystem"
StartPassword 	= ""
sName		= "MyService"
sDisplayName	= "My Interactive Service"
sPathName	= "c:Program FilesMyServiceMyService.exe"
bDeskInteract	= TRUE
iErrorControl	= 1

Set oInstance = GetObject("winmgmts:{impersonationLevel=impersonate}//" & _ 
	sComputer & "/root/cimv2:Win32_Service")

Set oMethod = oInstance.Methods_("Create")
Set oInParam = oMethod.inParameters.SpawnInstance_()
oInParam.Name = sName
oInParam.DisplayName = sDisplayName
oInParam.PathName = sPathName
'--oInParam.ServiceType = iServiceType
'--oInParam.ErrorControl = iErrorControl
oInParam.StartMode = sStartMode
oInParam.DesktopInteract = bDeskInteract
'--oInParam.StartName = sStartName
'--oInParam.StartPassword = sStartPassword
'--oInParam.LoadOrderGroup = sLoadOrderGroup
'--oInParam.LoadOrderGroupDependencies = aLoadOrderGroupDependencies
'--oInParam.ServiceDependencies = aServiceDependencies

Set oOutParam = oInstance.ExecMethod_("Create", oInParam)

If oOutParam.ReturnValue = 0 Then
	WScript.Echo "Service " & sName & " created successfully"
Else
	WScript.Echo "Create method for service " & sName & " failed"
	Select Case oOutParam.ReturnValue
		Case 1	WScript.Echo "Not Supported"
		Case 2	WScript.Echo "Access Denied"
		Case 3	WScript.Echo "Dependent Services Running"
		Case 4	WScript.Echo "Invalid Service Control"
		Case 5	WScript.Echo "Service Cannot Accept Control"
		Case 6	WScript.Echo "Service Not Active"
		Case 7	WScript.Echo "Service Request Timeout"
		Case 8	WScript.Echo "Unknown Failure"
		Case 9	WScript.Echo "Path Not Found"
		Case 10	WScript.Echo "Service Already Running"
		Case 11	WScript.Echo "Service Database Locked"
		Case 12	WScript.Echo "Service Dependency Deleted"
		Case 13	WScript.Echo "Service Dependency Failure"
		Case 14	WScript.Echo "Service Disabled"
		Case 15	WScript.Echo "Service Logon Failure"
		Case 16	WScript.Echo "Service Marked For Deletion"
		Case 17	WScript.Echo "Service No Thread"
		Case 18	WScript.Echo "Status Circular Dependency"
		Case 19	WScript.Echo "Status Duplicate Name"
		Case 20	WScript.Echo "Status Invalid Name"
		Case 21	WScript.Echo "Status Invalid Parameter"
		Case 22	WScript.Echo "Status Invalid Service Account"
		Case 23	WScript.Echo "Status Service Exists"
		Case 24	WScript.Echo "Service Paused"
End If	

The Remove method allows you to remove either the service you created with the Create method or one of the existing Windows services. Remember that before a service can be removed, it should first be stopped (the service deletion does not take effect until the service stops). Deletion also does not remove service-related files, only the relevant registry entries in HKLMSYSTEMCurrentControlSetServices key. This is why the recommended method for removing standard Windows services is through the use of SYSOCMGR.EXE.

Microsoft Knowledge Base article Q222444 provides additional details.

The following sample script removes the previously installed service.

sComputer 	= "REPLACE ME !!!!"	'replace with name of target computer
sName		= "MyService"

Set oInstance = GetObject("winmgmts:{impersonationLevel=impersonate}//" & _ 
	sComputer & "/root/cimv2:Win32_Service=" & Chr(34) & sName & Chr(34))

oInstance.StopService

iRetVal = oInstance.Delete

WSCript.Echo iRetVal

If iRetVal = 0 Then
	WScript.Echo "Service " & sName & " created successfully"
Else
	WScript.Echo "Create method for service " & sName & " failed"
	Select Case iRetVal
		Case 1	WScript.Echo "Not Supported"
		Case 2	WScript.Echo "Access Denied"
		Case 3	WScript.Echo "Dependent Services Running"
		Case 4	WScript.Echo "Invalid Service Control"
		Case 5	WScript.Echo "Service Cannot Accept Control"
		Case 6	WScript.Echo "Service Not Active"
		Case 7	WScript.Echo "Service Request Timeout"
		Case 8	WScript.Echo "Unknown Failure"
		Case 9	WScript.Echo "Path Not Found"
		Case 10	WScript.Echo "Service Already Running"
		Case 11	WScript.Echo "Service Database Locked"
		Case 12	WScript.Echo "Service Dependency Deleted"
		Case 13	WScript.Echo "Service Dependency Failure"
		Case 14	WScript.Echo "Service Disabled"
		Case 15	WScript.Echo "Service Logon Failure"
		Case 16	WScript.Echo "Service Marked For Deletion"
		Case 17	WScript.Echo "Service No Thread"
		Case 18	WScript.Echo "Status Circular Dependency"
		Case 19	WScript.Echo "Status Duplicate Name"
		Case 20	WScript.Echo "Status Invalid Name"
		Case 21	WScript.Echo "Status Invalid Parameter"
		Case 22	WScript.Echo "Status Invalid Service Account"
		Case 23	WScript.Echo "Status Service Exists"
		Case 24	WScript.Echo "Service Paused"
End If	

If the functionality provided by the Create method does not meet your requirements, you have a few other options. The SRVANY utility included in the Microsoft Windows Resource Kit functions as a wrapper for an application that must run as a service. Like the Win32_Service Create method, SRVANY creates appropriate registry entries and, in addition, handles communication with Service Control Manager. Similar capabilities are offered by Firedaemon, a Lite version of which is freely downloadable from the vendor’s Web site.

Get the Free Newsletter!

Subscribe to Daily Tech Insider for top news, trends & analysis

Latest Posts

Related Stories