Windows XP Services, such as the IIS web server service, the FTP daemon service, or the Remote Desktop service, can be managed with the Services MMC snap-in (discussed in Chapter 8). Rudimentary service control is also possible with WSH scripts. The following routine allows you to start and stop any service, or just see if a service is running:
Function Service(ServiceName, Action) Const SERVICE_STOPPED = 1 Const SERVICE_RUNNING = 4 Set WshShell = WScript.CreateObject("WScript.Shell") Set EnvObject = WshShell.Environment("PROCESS") ComputerName = EnvObject("COMPUTERNAME") Set ComputerObject = GetObject("WinNT://" & ComputerName & ",computer") Set ServiceObject = ComputerObject.GetObject("Service",ServiceName) If Action = 1 and ServiceObject.Status = SERVICE_STOPPED Then ServiceObject.Start ElseIf Action = 2 and ServiceObject.Status = SERVICE_RUNNING Then ServiceObject.Stop End If If ServiceObject.Status = SERVICE_RUNNING Then Service = True Else Service = False End If End Function
This general-purpose routine accepts two parameters: ServiceName and Action. ServiceName is a single word that represents the service you wish to start, stop, or query, and Action is just a number, representing what you want the routine to do. To find the service name for a given service, open the Services window (services.msc) and double-click the service in question. The service name is listed at the top of the General tab; for example, the service name for the IIS service is IISADMIN, the name for the FTP service is MSFTPSVC, and the name for the Remote Desktop (a.k.a. Terminal Services) service is TermService.
So, to start the FTP service, you would type:
Result = Service("MSFTPSVC", 1)
or, to stop the service, you would type:
Result = Service("MSFTPSVC", 2)
Either way, the function returns True (-1) if your action resulted in the service being started, or False (0) if your action resulted in the service being stopped. To simply query the service, without starting or stopping it, specify any other number for Action, like this:
Result = Service("MSFTPSVC", 0)
Including this routine in your script would allow you to start and stop a service with a single click (rather than having to wade through the Services window). Or, using these script routines in conjunction with Scheduled Tasks (explained later in this chapter), for example, you could schedule your web server service to operate only during certain hours of the day. See Chapter 8 for more information on Services and the Microsoft Management Console.