Subscribe to Windows IT Pro
June 12, 2006 12:00 AM

Run Your Scripts as Services

This HTA makes it easy
Windows IT Pro
InstantDoc ID #49900
Rating: (2)
Downloads
49900.zip

Connecting to the target computer. The HTA uses Windows Management Instrumentation (WMI) to connect to the target computer and to retrieve and set the information required for the service to function correctly. On remote computers, you need administrative privileges to create the service. If needed, you can specify alternate credentials for the remote connection in the HTA UI. If you're already an administrator on the remote computer, you can leave these text boxes blank.

After the connection is made, the HTA finds the %systemroot% folder using the Win32_OperatingSystem class's SystemDirectory property. With this information, the HTA can copy the files needed (mainly srvany.exe and the script to run as the service) to the correct location and write the correct location to the registry to let the service know where to find the files. If the HTA can't copy the files, it will attempt to map a network drive (Z: to Admin$system32) using the alternate credentials provided and try to copy the files from that location. The script exits if the files can't be copied.

Creating the service. The HTA uses the Win32_BaseService class's Create method to create the service on the target computer. The Create method accepts up to 12 parameters. The HTA sets about half of them:

  • The first parameter specifies the name of the service. In this case, the Service variable contains this value, which the HTA retrieves from the second text box in the UI.
  • The second parameter specifies the service's display name. The HTA uses the Service variable's value for the display name.
  • The third parameter specifies the fully qualified path to the executable file that implements the service (in this case, srvany.exe).
  • The fourth parameter specifies the type of service. The HTA sets the service type as Own Process (value of 16), which means the script will run in its own process. To make it easy for others to discern the service type when reviewing the HTA code, a constant named OWN_ PROCESS specifies the service type.
  • The fifth parameter indicates the severity of the error if the Create method fails to start when the computer restarts. The HTA uses a constant (NORMAL_ERROR_CONTROL) to specify the Normal level (value of 1), which means the user will be notified if a failure occurs.
  • The sixth parameter specifies the service's startup mode. The HTA sets this parameter to Automatic, which means the service starts up whenever the computer is restarted.
  • The seventh parameter determines whether the service can interact with the desktop. The HTA uses the NOT _INTERACTIVE constant to tell the service not to interact with the desktop.

To learn about the other parameters you can set for the Create method, go to http://www.msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/create_method_in_class_win32_baseservice.asp.

Configuring the service's registry settings. Without some registry edits, the service won't run. So, the HTA uses WMI's StdRegProv class to make the necessary registry changes, as callout A in Listing 2 shows. This class provides methods for writing to and reading from the registry.

The HTA first creates a registry key named HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services/service_name, where service_name is the name of the service you're creating. The HTA then adds a Parameters subkey. In the Parameters subkey, the HTA adds two entries, as callout B in Listing 2 shows. The first entry is named Application. To this entry, the HTA assigns a REG_SZ value that specifies the path to WScript (which will execute the script that runs as a service) and the path to the script. The second entry is named Description. To this entry, the HTA assigns a REG_SZ value that describes the service. The HTA retrieves this value from the third text box in the UI. The description is a nice addition because anyone who looks at the Control Panel Services applet will know what the service is for.

Starting the service. After the registry changes are made on the target computer, the service is ready to be started. The HTA uses the Win32_ Service class's StartService method to start the service. Note that anytime you make changes to the script, you need to restart the service for the changes to become effective.

Displaying the script's progress. To display the progress of the script that's running as a service, the script opens an IE window. Using an IE window to display a script's progress is necessary because the typical approaches don't work. For example, you can't use VBScript's MsgBox function or the WScript.Shell object's Popup method because they would cause the HTA to pause during execution. (Although the HTA uses a message box to prompt the user to enter the path to srvany.exe when that utility can't be found, that pause isn't detrimental because the script can't run without that path anyway.) You can't use the Echo method because it's an object intrinsic to the WScript and CScript engines, and HTAs use mshta.exe for execution. You can't display progress messages in the HTA UI because the script would appear to hang. Even though the script would be running, you wouldn't see any progress messages. You're get the progress messages only after the script finished running or if the script stopped running due to an error. By using an IE window, the HTA can provide progress reports the entire time the script is running.

How to Adapt a Script
As I mentioned previously, scripts that need to run continuously are good candidates for running as services. For example, the MoveFiles.vbs script in Listing 3 would be a good candidate. This script uses the FileSystemObject object to move to a network share any files that users save to a local folder named C:\TempImages. Note that this script doesn't report results or handle errors. So, if you want to use this script in a production environment, you'll need to make it more robust by adding code that would handle errors and report results.

It's important to keep in mind that whatever script you intend to run as a service must run totally unattended. Otherwise, the script might fail. For example, if a script that uses the MsgBox function were to run under the WScript engine, the script would display a message box and wait for you to click a button before the script continued. But you might not see the message box if the script were running under an account that differs from the one you're currently logged on with, so the script would wait indefinitely. You could run the script with CScript, but you run the risk of having a command window pop up if certain service parameters are set.

The bottom line is that you need to avoid using such elements as the MsgBox function and the Popup method. You should also avoid using the WScript object's Echo method. However, if you want to leave an Echo statement in a script for testing purposes later, you can insert the code

WScript.interactive = False 
at the beginning of the script to disable all prompts, as callout A in Listing 3 shows.

If you want to remove an HTAcreated service, the Microsoft TechNet Script Center (http://www.microsoft.com/technet/scriptcenter/default.mspx) has a script to remove services on local or remote machines.

2 Tools for the Job
You need the right tools to successfully run your systems administration scripts. When it comes to scheduling scripts to run, you have at least two tools at your disposal. Under many circumstances, Schedule Tasks works well to run scripts. However, when you need a script to run continuously or when you need to know immediately if a script fails, you should consider running the script as a service.

Related Content:

ARTICLE TOOLS

Comments
  • bsadmin
    2 years ago
    Oct 27, 2010

    this looks/feels like a great tool. i need assist/confirmation to use this tool to execute a batch that executes the 'net use' command to map a network share as a drive letter. unlike the move files sample, which maps a drive every 30 seconds, my batch executes once. does this static mapping stay in background, will it be impacted if an admin logs onto the server? we want to keep the share connection in place as there is another application that runs and monitors that share for files that are generated constantly/realtime... thanks for any insight!

  • kbemowski@scriptingprovip.com
    4 years ago
    Feb 28, 2008

    FYI -- If you use passwords in VBScript or JScript scripts, running those scripts as services is the best way to protect those passwords. See "3 Ways to Protect Passwords in WSH Scripts" (InstantDoc ID 44580) for more information.

    "3 Ways to Protect Passwords in WSH Scripts" also tells you how to manually use srvany.exe to install a script as a service. Using the Install_ Service HTA is much simpler than manually using srvany.exe!

  • Simon
    4 years ago
    Feb 27, 2008

    reasonable

You must log on before posting a comment.

Are you a new visitor? Register Here

advertisement

advertisement

Windows is a trademark of the Microsoft group of companies. Windows IT Pro is used by Penton Media Inc. under license from owner.