This article is the third in a series of Windows Web Solutions articles that describe how to use Microsoft Active Directory Service Interfaces (ADSI) scripts to read, configure, and administer your Web servers. Microsoft Internet Information Services (IIS) 5.0 Help includes a topic called Administrative Scripts, so spending so much time discussing ADSI scripts and how to use them to manage IIS might seem redundant. The documents in the Administrative Scripts topic each describe a command that you can use to administer IIS. These commands are useful ADSI scripts, but they don't show you how to write your own ADSI scripts. My articles are intended to help you create customized script solutions for managing your IIS implementations.
In the first two articles—"How to Use a Script to Access and Read the Metabase," October 2002, http://www.windowswebsolutions.com, InstantDoc ID 26261, and "Use Scripts to Configure IIS," December 2002, InstantDoc ID 26932—I explain how to read attributes from and write attributes to the IIS metabase. In this article, I address IIS Admin Object methods that create, delete, and perform object-specific actions in IIS. Although this article isn't an exhaustive exploration of every IIS Admin Object and its methods, I've carefully selected methods that perform key administrative tasks in IIS. Specifically, I demonstrate how to create and delete Web sites; control site status (such as starting and stopping a Web site); and perform backup, restore, and backup management operations against the IIS metabase.
Creating a Web Site
I would venture to guess that every IIS administrator creates and deletes Web sites from time to time. Typically, before creating a Web site, you create a file-system folder. Then, you create and configure the Web site and a root virtual directory that points to the folder you created in the file system. For an example of how to use Windows Management Instrumentation (WMI) to create a folder and set NTFS permissions on it, see "Create Home Directories and Set NTFS Permissions with a Web Script," September 2001, http://www.windowswebsolutions.com, InstantDoc ID 22048.
To use ADSI to create and configure a Web site, you use properties and methods of two ADSI core interfaces: IADsContainer and IADs. IADsContainer provides the Create method for creating objects in the IIS metabase. IADs contains the Put and PutEx methods for configuring the metabase and the SetInfo method for committing (saving) objects to the metabase. Windows XP Professional Edition and Windows 2000 Professional support only one Web site instance—the Default Web Site; therefore, attempting to use a script to create a Web site on either of these client platforms will fail. Follow these steps to create a Web site on Win2K Server:
- Bind (connect) to the IIS Web service.
- Create a new Web site.
- Assign attributes to the Web site.
- Commit the Web site to the metabase.
- Create a virtual root directory.
- Assign attributes to the virtual root directory.
- Commit the virtual root directory to the metabase.
The script that Listing 1 shows goes a bit further than these seven steps: The script starts the Web site after creating it and configures all the attributes that appear when you run the Web Site Creation Wizard from the Microsoft Management Console (MMC) Internet Information Services snap-in. These attributes are only a small subset of the attributes that you can configure in IIS. For more information about configuring other attributes, see the first two articles in this series. I've omitted error-checking and initial variable dimensioning to keep the script simple. I've included constant definitions because they make the script easier to understand.
To begin, I define five constants that the script uses later. The script's first action is to bind to the W3SVC because a script must bind to some point in the metabase hierarchy before it can work with the metabase. For more information about this step, see "How to Use a Script to Access and Read the Metabase."
Scripts use an integer called the Web server index or instance ID to refer to Web sites. When you create a Web site, you must specify the Web server index as a required parameter on the Create method. You can specify any available number as the Web server index. For example, if you have four Web sites with indexes 1 through 4, the next available Web server index is 5. You could specify 9 as the index if you so desired, but for the sake of organization, you should use 5.
The code at callout A in Listing 1 determines the next available Web server index. The metabase can contain objects other than Web sites (e.g., FTP sites), so the script uses a For Each loop and the IADs Class property to count objects that are derived from the IIsWebServer class. After counting the Web sites, the script adds 1 to the intWebServerIndex variable so that the variable contains an integer equal to the next available Web server index.
In the code at the end of callout A, intWebServerIndex appears as the second parameter of the Create method call. The first parameter, IIsWebServer, is the class of object I want to create. The ADSI Class property is synonymous with the KeyType property of the lIS Admin Object.
Notice that the script uses the Set statement to create the objIIsWebServer object reference in memory. As the code at callout B in Listing 1 shows, the IADs Put and PutEx methods then configure the objIIsWebServer object attributes. The ADS_PROPERTY_UPDATE constant appears in the PutEx method call. This constant instructs the method to overwrite anything that's currently stored in the attribute being written. After the Put and PutEx methods configure the Web site's attributes, the IADs SetInfo method commits the Web site to the metabase.
The script completes the Web site—creation process by creating a virtual root directory for the Web site, assigning attributes to the directory, and committing it to the metabase. The code at callout C in Listing 1 creates the virtual root directory. The script calls the IADs Create method and uses the objIIsWebServer object as its container. The Create method's first parameter specifies the IIsWebVirtualDir virtual directory object; the second parameter, ROOT, instructs the script to create a virtual root directory.
Next, the script sets the path to the folder in the file system that contains your Web site. The script in Listing 1 specifies a local path of d:\inetpub\vdirRoot; however, if you specify a Universal Naming Convention (UNC) path such as \\server4\vdir, IIS can set the path to a share on another computer. If you use a redirection URL instead of a local path or UNC path, you must use the HttpRedirect attribute instead of the Path attribute. To learn more about the HttpRedirect attribute, see HttpRedirect in the IIS 5.1 software development kit (SDK) or go to http://msdn.microsoft.com/library/default.asp?url=/library/en-us/iisref/htm/ref_mb_httpredirect.asp. To learn more about HTTP redirection, see "Virtual Directories: HTTP Redirection," October 2002, http://www.windowswebsolutions.com, InstantDoc ID 26256.
The script then configures access rights (in this case, Read and Script) to the Web site. You configure the Read right by setting the AccessRead attribute to True, and you configure Execute rights by setting the AccessScript attribute to True. These rights are inheritable from the Web server's Master Properties, but by configuring them on the Web site you're creating, you ensure appropriate permissions for the site. For more information about the many other access rights you can configure for a Web site, see AccessFlags at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/iisref/htm/ref_mb_accessflags.asp.
After the script configures access rights, it sets the AuthFlags attribute, which specifies the authentication method or methods allowed on the Web site. The script configures two authentication methods: Anonymous access and Integrated Windows authentication. However, you can also use the AuthFlags attribute to set the other two authentication methods—Basic and Digest. Notice that the script adds the two authentication constants, MD_AUTH_ANONYMOUS and MD_AUTH_NT, together on the call to the IADs Put method. Instead of spelling out the constant names, you could specify the sum of the constant values (6), but including the names makes the script easier to read later when you come back to it. Like access rights, authentication methods are inheritable from the Web server's Master Properties.
The last two attributes you configure for the virtual root directory are an application named Default Application and an application protection level. These attributes and the AccessScript attribute are part of a Web site's application settings. In the code at callout C, the AppCreate2 method sets the application protection level to medium (pooled). The POOLED constant is one of three constants available to the AppCreate2 method. The other two constants support low (IIS process) and high (isolated) protection levels. An AppCreate method exists, but this script doesn't use it because it doesn't support the medium setting. After configuring the virtual root directory's attributes, the script uses the IADs SetInfo method to complete the last step in creating a Web site—committing the virtual root directory to the metabase.
Controlling Site Status
After you create a Web site, you need to use the Start method to start the Web site; it doesn't start automatically. The Start method, which the code at callout D in Listing 1 calls, is part of the IIsWebServer object. The script then uses the Status method of the IIsWebServer object to check the server's status. If the script returns a status value of 2, the site started. Rather than check for the integer value, the script uses the SITE_STARTED constant to make the script easier to read. If any other value is returned, the site didn't start successfully.
Table 1 lists other IIsWebServer object methods that control the Web server's status. The Pause method pauses a running server, the Continue method restarts a paused server, and the Stop method stops a running server. You call these methods the same way the code at callout D calls the Start method. Notice that the table's last column is labeled Suggested Constant Name. These names are arbitrary because VBScript files that Windows Script Host (WSH) runs don't support constants defined in type libraries. Only Windows Script File (.wsf)formatted script files support type libraries. In addition, a defined type library containing an enumeration (a set of constants) for the status methods doesn't exist. If you aren't familiar with .wsf files and type library support, see "Windows Script Files in Action," June 2000, http://www.winnetmag.com, InstantDoc ID 8631.
Before you call a method that changes a Web site's status, you must determine the current status. You don't want to call the Stop method, as the code in Listing 2 shows, if the site is already stopped. To determine a Web site's status, you bind to the Web service and specify the Web server index of the Web site whose status you want to know.
You'll likely know the Web site description (which the ServerComment attribute contains) but not the Web server index number. The code at callout A in Listing 2 enumerates all Web sites by index number to find the site with a ServerComment attribute of NewSite. I've hard-coded the name NewSite into the script, but you can hard-code a different name or use the WshArguments object in WSH 5.6 or later to specify the name as a command-line parameter. For more information about WSH named arguments, see "VBScripting Solutions: Take Advantage of Named Arguments," June 2002, http://www.winscriptingsolutions.com, InstantDoc ID 24943.
After the script binds to the appropriate Web site, the code at callout B in Listing 2 checks the Web site's status. If the Web site is running, the script calls the IIsWebServer Stop method to stop the site. The script then uses the WScript Sleep method to wait for 3 seconds, rechecks the site's status, and returns the Web site's status.
Deleting a Site
Deleting a Web site is far simpler than creating a Web site. After you bind to the W3SVC, you simply specify the Web server index number of the Web server that you want to delete. Like the script in Listing 2, the script in Listing 3 finds the Web site by using the value stated in the ServerComment attribute. Then, the code deletes a site named NewSite from the Web server.
Backing Up and Restoring the Metabase
No administrative solution for a directory service such as the IIS metabase would be complete without a way to back up and restore the metabase directory. The IISComputer object, which is at the top of the metabase hierarchy, provides two methods for backing up the metabase—Backup and BackupWithPassword—and two methods for restoring the metabase—Restore and RestoreWithPassword. As the names suggest, one method requires that you specify a password and the other doesn't. Specifying a password when you perform a backup provides some security because if you use the BackupWithPassword method to back up the metabase, you must use the RestoreWithPassword method to restore the metabase. To keep the script samples as simple as possible, I use the simpler Backup and Restore methods, which Listing 4 and Listing 5 show, respectively.
Running the script in Listing 4 creates a backup file named IISBackups.MD0 in the %systemroot%\system32\inetsrv\metaback folder. The backup filename is designated by the first parameter of the Backup method. If you don't specify a name for the first parameter of the Backup method, IIS automatically names the file MDBackup. The second parameter, MD_BACKUP_NEXT_VERSION, instructs the Backup method to increment the backup file name by 1 on each subsequent script run. Thus, running the script a second time creates the file IISBackups.MD1. The last parameter, intBackupFlags, specifies how the backup behaves when files with the same prefix already exist in the backup folder. By default, a copy of the file is always saved when the backup is run, but the second flag, MD_BACKUP_FORCE_BACKUP, which forces the backup to run, requires that the first flag, MD_BACKUP_SAVE_FIRST, be specified to work properly. Additional parameters help control the backup routine's behavior. Consult the IIS documentation for details about these parameters.
The Backup and Restore methods are powerful tools for metabase recovery. You should use the Restore method to restore the IIS configuration only to the machine on which it was created. Listing 5 shows how to use the Restore method to restore the metabase. The Restore method is a bit simpler than the Backup method. The first parameter is the prefix of the backup file you want to restore. The second parameter can be either MD_BACKUP_HIGHEST_VERSION, as Listing 5 shows, or the version number of the backup you want to restore. The last parameter is 0; you must specify this parameter or the Restore method won't work. This value is a reserved parameter and is used only as a placeholder in the current version of the Restore method.
The IISComputer object has two methods for managing metabase backups: EnumBackups and DeleteBackup. The EnumBackups method lets you view details about existing backups, and the DeleteBackup method deletes existing backups.
Listing 6 shows a .wsf script that enumerates backups. I use .wsf format in this case (instead of the VBScript I used in earlier scripts) because this script draws upon both JScript and VBScript to provide details about existing backups. The EnumBackups method returns version, location, and backup date information. The method's first two parameters, BkupLocIn and IndexIn, provide EnumBackups the location of the backup files and the index number, starting at 0, of the backup to enumerate. If you specify an empty string for the BkupLocIn parameter, EnumBackups searches all backup locations.
EnumBackups returns date information in Universal Time Coordinate (UTC) form, which means that the script adjusts the date and time it returns to match the time zone of the computer on which the script runs. Typically, you run this type of script on the IIS server on which you created the backups. Thus, the date and time information returned is based on the IIS server's time zone. The JScript code at callout A in Listing 6 uses the JScript Date object to return the computer's time zone as an offset of Greenwich Mean Time (GMT). The intMinDifference variable stores this offset value, which the script later uses to convert the UTC time to local time. If you run the backup routine that Listing 4 shows three times, the backup enumeration script that Listing 6 shows will return something like the following:
Date: 9/22/2002 10:13:56 PM
1. IISBackups (Ver. 1)
Date: 9/23/2002 8:00:58 PM
2. IISBackups (Ver. 2)
Date: 9/24/2002 11:14:00 PM
The DeleteBackup method has two parameters. The first parameter is the backup file prefix, and the second parameter is the backup version to delete. As with the Restore method's second parameter, DeleteBackup's second parameter can be a specific version number or you can specify MD_BACKUP_HIGHEST_VERSION to instruct the DeleteBackup method to delete the most recent backup. Listing 7 shows a script that deletes the last version of a backup named IISBackups.
The IIS Help documentation states that you shouldn't use the metabase backup and restore facility for cross-machine replication. Therefore, don't use the restore method to restore a metabase to another computer. Instead, create one script that you can use as a template to add sites to and configure sites for any IIS computer.
This article shows you how to use ADSI scripts to create and configure Web sites and perform some important IIS management tasks. Although I focus on Web server components, you can apply the same principals to scripting other IIS services such as SMTP and FTP sites.