November 2010 (1)
August 2010 (1)
July 2010 (1)
June 2010 (3)
July 2009 (3)
June 2009 (1)
May 2009 (1)
February 2009 (1)
January 2009 (1)
November 2008 (3)
October 2008 (4)
September 2008 (9)
August 2008 (6)
July 2008 (3)
June 2008 (3)
January 2008 (1)
November 2007 (2)
October 2007 (6)
September 2007 (5)
August 2007 (22)
July 2007 (6)
June 2007 (1)
May 2007 (3)
April 2007 (27)
March 2007 (8)
February 2007 (6)
September 2006 (2)
August 2006 (4)
July 2006 (9)
June 2006 (17)
May 2006 (20)
April 2006 (12)
March 2006 (9)
February 2006 (4)
January 2006 (3)
December 2005 (2)
November 2005 (4)
October 2005 (5)
September 2005 (37)
August 2005 (83)
July 2005 (6)

Active Directory / LDAP (0)
ASP.Net (19)
Blackberry Development (4)
c# (34)
c++ (3)
Code Camp (1)
Excel (1)
Exchange (3)
Front Page 2003 (6)
FTP User Editor (4)
HTML / CSS / DHTML (8)
IIS (146)
IIS - Log Parser (7)
IIS / FTP (12)
IIS / Tools / Administration (42)
IIS / Tools / Authentication (6)
IIS / Tools / Compression (8)
IIS / Tools / Crash & Hang (12)
IIS / Tools / ISAPI Filters (17)
IIS / Tools / Log Files (17)
IIS / Tools / Scripts (28)
IIS / Tools / Security (9)
IIS / Tools / SSL (6)
IIS 7 (3)
Internet Information Server (1)
Me (Chris Crowe) (6)
MIME Types (1)
Misc (72)
Oulook Express (2)
Silverlight (1)
SQL Server (27)
SQL Server CTE (1)
Vista (15)
Vista Gadgets (8)
Visual Studio (11)
Voice over BroadBand (1)
Windows (33)
Windows Powershell (3)
Windows Sharepoint Services (0)
Windows Sharepoint Services (15)
Windows Vista (14)
Wine Cellar (1)
WMI (8)
IIS / Tools / Scripts (28) blog.crowe.co.nz.Models.Category

IIS / Tools / Scripts

Starting and Stopping a Web Site And Application Pool

I had a request last week for the following:

I'm trying to do the following:

  1. Stop a IIS website
  2. Stop an App Pool
  3. Start the App Pool
  4. Start the Website

From what I can see here, I can use the example for the "starting an application pool" for the steps 2 & 3.

I have found that you can use iisweb.vbs to do steps 1 & 4.

 But how link them in the order above?

 Hope you can give me some pointers

 

The following code sample in VBScript allows you to do that with the following points of interest.

  • The Default Web Site is assumed - WebSiteID = 1, you can change this to any other web site by changing the ID with the ID of the other web site. There is a script called FindWeb.VBS or you can look at the log folder name and get the web site id from that - see http://blog.crowe.co.nz/archive/2007/08/04/IIS-Web-Site-Identifiers.aspx
  • There is only 1 site using the AppPool - well not technically true, if you run this and there is more than one web site using the app pool then it will be down while the app pool restarts.

Here is the code, save to StopAndStartSiteAndAppPool.VBS file and then run in a CMD.EXE prompt using the following syntax:

cscript StopAndStartSiteAndAppPool.VBS

 

Option Explicit

Dim WebSiteID, objWebSite, ObjAppPool

WebSiteID = "1"
Set objWebSite = GetObject("IIS://localhost/W3SVC/" & WebSiteID)
WScript.Echo "Stopping Web Site : " & objWebSite.ServerComment \
objWebSite.Stop()

wscript.echo "Stopping Application Pool : " & objWebSite.AppPoolID
Set objAppPool = GetObject("IIS://localhost/W3SVC/AppPools/" & objWebSite.AppPoolID)
objAppPool.Stop()

wscript.echo "Starting Application Pool : " & objWebSite.AppPoolID
objAppPool.Start()

WScript.Echo "Starting Web Site : " & objWebSite.ServerComment
objWebSite.Start()

You can also view/save the script from here.


IIS Web Site Identifiers

Normally you do not need to be concerned about web site identifiers, these are the actual ID's that reference the web site to IIS. Normally we just use the web site description such as Default Web Site or in my case blog.crowe.co.nz or something similar.

But if you are interested in writing scripts you normally reference sites using the Web Site Instance ID.

In IIS 6 the IIS Manager shows you a column called Idenfitier and this is the actual ID that references the web site. This was not visible in Windows 2000 (IIS 5) or Windows XP (IIS 5.1) and we had to use different methods to see the identifier.

Using IIS 7 on Windows Vista you can see a column called ID which is the Web Site Instance ID

The Default Web Site always has an identifier of 1.

All other web sites on IIS 6 have web site idenfieir's that look like random numbers. The fact is that this is not the case and the identifier is generated based on the description of the web site. This is so that if you have a server farm as long as the descripiton is the same you will end up with the same web site identifier. See this article for more details on the way that these identifiers are generated.

 Another way to identify the web site instance id is to look at the Logging Properties of a particular web site.

As you can see above the highlighted area shows the web site instance id. This is still a valid method for people using IIS 5 and IIS 5.1.

IIS 7 on Windows Vista does not include a logging configuration option - did they just forget it?

How about if you want to use a script to identify a web site?

IIS comes with a script called findweb.vbs that you can use to find a particular web site. This script is stored in c:\inetpub\adminscripts by default.

To use it you need to open a CMD.EXE command prompt and then use the cscript.exe utility to run the script. You also need to specify parameters to get the script to do what you want.

In this case I was interested in finding a web site called photos.crowe.co.nz

How about writing your own VB Script to list the site and the instance id?

Running the script above will display the web site Instance ID and the Description of the site.

 


Microsoft releases a new download center for IIS (everything in one place)

DownloadCENTER for IIS.net has been released! 

The DownloadCENTER at IIS.net, is a community hotspot for discovering, sharing, reviewing and promoting IIS-related solutions in a single place.  Dozens of existing downloads, for all versions of IIS – both from Microsoft and the community – are already available in DownloadCENTER today. 

This new feature of IIS.net is particularly relevant with the release of IIS7 in Windows Vista.  The latest release of Microsoft’s Web server has a completely modular architecture which features over forty pluggable components that can be easily added, removed or even replaced with custom implementations. 

This powerful extensibility support is available to both .NET and C/C++ developers.  In the future, DownloadCENTER is expected to house a large number of IIS7 extensions submitted by not only the IIS team but the developers and partner ISVs of the IIS community as well.

To learn more about the DownloadCenter, read IIS Product Unit Manager, Bill Staples’ blog post about it or check it out yourself today!

 


VBScript - Check if multiple version of the .NET framework are assigned to an application pool

This code will allow you to check if there are IIS applications which are configured to use multiple version of the .NET framework.

The code enumerates all the Application Pools and then find all of the applications in that pool. It then checks for the version of the .NET framework which handles the .ASPX file extension.

It saves the unique versions of the .NET Framework found and if it finds multiple versions installed will list all of the applications using that Application Poll and display the path and the version being used. This will allow you to find a potential problem which could be hard to track down normally.

Calling Usage 

cscript CheckForMultipleVersionsOfDotNetFramework.vbs

Example Output

AppPool #1
No applications using this pool!

DefaultAppPool

 Warning multiple version of the .NET framework detected!

 Found references to v1.1.4322
 Found references to v2.0.50727

 //localhost/W3SVC/1/ROO                                           - v1.1.4322
 //localhost/W3SVC/1198258389/ROO                         - v1.1.4322
 //localhost/W3SVC/1280263431/ROO                         - v1.1.4322
 //localhost/W3SVC/1388032739/ROO                         - v1.1.4322
 //localhost/W3SVC/1849151055/ROO                         - v1.1.4322
 //localhost/W3SVC/1957176745/ROO                         - v1.1.4322
 //localhost/W3SVC/4/ROO                                           - v1.1.4322
 //localhost/W3SVC/415889539/ROO                           - v1.1.4322
 //localhost/W3SVC/1/ROOT/Monito                            - v2.0.50727
 //localhost/W3SVC/1/ROOT/Monitorin                        - v1.1.4322
 //localhost/W3SVC/1/ROOT/NetTracke                       - v1.1.4322

ExchangeApplicationPool
Found references to v1.1.4322

ExchangeMobileBrowseApplicationPool
Found references to v1.1.4322

MSSharePointAppPool
Found references to v1.1.4322

MyAppPool1
No applications using this pool!

Source Code

You can download the source code here.

option explicit
dim AppsInPool, objAppPool, index, IISObj, IISPath, Version, pos
Dim Versions(), objAppPools
function FindASPXScriptMapVersion(ScriptMaps)
 Dim pos, ScriptMap
 for pos = lbound(ScriptMaps) to UBOund(ScriptMaps)
   ScriptMap = lcase(ScriptMaps(POS))
   if (left(ScriptMap, 5) = ".aspx") then
    FindASPXScriptMapVersion = mid(ScriptMap, 42)
    FindASPXScriptMapVersion = left(FindASPXScriptMapVersion, _
     instr(FindASPXScriptMapVersion, "\")-1)
    exit function
   end if
 next 
 FindASPXScriptMapVersion = ""
end function
function AddVersion(Version, Path)
 dim Found, pos
 Found = false
 for pos = lbound(Versions) to UBound(Versions)-1
  if (Versions(pos) = Version) then
   Found = true
  end if
 next
 if (Found = false) then
  redim preserve Versions(ubound(Versions)+1)
  Versions(ubound(Versions)-1)= Version
 end if
end function
Set objAppPools = GetObject("IIS://localhost/W3SVC/AppPools")
for each objAppPool in objAppPools
 Redim Versions(0)
 Set objAppPool = GetObject("IIS://localhost/W3SVC/AppPools/" & objAppPool.Name )
 WScript.echo objAppPool.Name 
 AppsInPool= objAppPool.EnumAppsInPool()
 if (ubound(AppsInPool) = -1) then
  WScript.echo vbtab  & "No applications using this pool!"
 else
  for index = lbound(AppsInPool) to UBound(AppsInPool)
   IISPath = AppsInPool(index)
   IISPath = "IIS://localhost/" & mid(IISPath,5, len(IISPath)-5)
   set IISObj = GetObject(IISPath)
   Version = FindASPXScriptMapVersion(IISObj.ScriptMaps)
   call AddVersion(Version, mid(IISPath,5, len(IISPath)-5))
  next
  if (ubound(Versions)> 1) then
   WScript.Echo vbcrlf & vbtab & _
    "Warning multiple version of the .NET framework detected!" & vbcrlf
   
   for pos = lbound(Versions) to ubound(Versions)-1
    WScript.echo vbtab & "Found references to " &  Versions(pos) 
   next
   WScript.echo ""
   for index = lbound(AppsInPool) to UBound(AppsInPool)
    IISPath = AppsInPool(index)
    IISPath = "IIS://localhost/" & mid(IISPath,5, len(IISPath)-5)
    set IISObj = GetObject(IISPath)
    Version = FindASPXScriptMapVersion(IISObj.ScriptMaps)
    WScript.echo vbtab & mid(IISPath,5, len(IISPath)-5) & _
     space(70 - len(IISpath)) & " - " & Version
   next
  else
   for pos = lbound(Versions) to ubound(Versions)-1
    WScript.echo vbtab & "Found references to " &  Versions(pos) 
   next  
  end if
 end if
 WScript.echo ""
next

IIS 6 - Creating an application and setting the application pool using ADSI
I received a request from visitor to my blog on how to set an application pool to a new folder he created.

"

I have a small web server running IIS 6 and I host small sites for friends and family all under one domain. To keep them separate I put each of their sites into a subfolder and drop it into different pools.

To date I've been doing this manually.  I've been trying to get my mind wrapped around this ADSI stuff to automate this process a bit but I'm coming up short.

Here's what I do now.. if you have a few moments can you tell me how I might go about automating this process?

  1. I make a subfolder (call it Test) in the root of my website.
  2. I go into IIS Manager, expand the website, then right click on Test / Properties.
  3. I click Create to make it into an application.
  4. I change the application pool from Default to "familypool" then Apply.
"

 

The following code will allow you to create an application and assign the application pool "familypool" to the new directory. Note the application pool “familypool“ must already have been created.

option explicit

dim IIsWebVDirObj
dim IIsWebVDirRootObj
dim NewFolderName

NewFolderName = "Test"

const CreateNewApplicationPool = true
const UseExistingApplicationPool = false


' Create the Metabase entry
Set IIsWebVDirRootObj = GetObject("IIS://LocalHost/W3SVC/1/Root")
Set IIsWebVDirObj = IIsWebVDirRootObj.Create("IIsWebDirectory", NewFolderName)

IIsWebVDirObj.AppCreate3 2, " familypool", UseExistingApplicationPool
IIsWebVDirObj.AppFriendlyName = "My App Friendly Name"
IIsWebVDirObj.SetInfo

 

In the code above we have made some assumptions:

  • The web site we are assigning it to is the default web site. This has an instance ID of 1.
  • The IISWebDirectory does not exist in the Metabase. If it does it will cause an error as would be the case if you run the code twice.

In the case of the 2nd assumption above we would need to change the code from

Set IIsWebVDirRootObj = GetObject("IIS://LocalHost/W3SVC/1/Root")
Set IIsWebVDirObj = IIsWebVDirRootObj.Create("IIsWebDirectory", NewFolderName)

to

' Load the Metabase entry if it does exist
Set IIsWebVDirObj = GetObject("IIS://localhost/W3SVC/1/Root/" & NewFolderName)
 


IIS 6 Application Pools and ADSI

An application pool provides you with a way of isolating Web sites and Directories from each other even though they are being hosted on a common server. Each application pool is given its own set of server resources and can be configured with different identities. That way, if a Web site crashes, it won’t effect sites in other application pools.

A example of this is a Web site which has a memory leak. If all of the Web sites hosted on a particular server were to share the system resources as was the case with IIS 5.1 and earlier and one of the Web sites had a memory leak, it could potentially take memory away from the other hosted sites.

If the leaky site were in its own application pool though, the memory leak would not effect any other site because each application pool has its own server resources including memory.

On earlier versions of IIS you could only configure your sites to run either Low ( In Process ) with the IIS Engine, Medium ( Pooled ) where all applications shared a pool of memory, and High (Out Of Process). The problem with this is that a bad application could depending on the isolation level take down the IIS server, or all other sites in the Medium ( Pooled ) model.

Each application pool can be recycled based on a memory limit, the time of day, a number of requests or just after a period of time. Each application pool can also run with its own identity which can be either Local System, Local Service, Network Service or a custom credential.

Application pools are available only when IIS is running in worker process isolation mode (this is the default). If you are running IIS in IIS 5 isolation mode, then the application pools will not be accessible to you.

There is only one application pool by default called DefaultAppPool. When you create new Web sites, the newly created sites by default will use the DefaultAppPool unless you reconfigure the site after it is created. IIS does not automatically create a separate application pool for each Web site.

Note: If you are running ASP.NET 1.1 and 2.0 then they must run in two different application pools as you can only load one version of the .NET framework into an application pool.

Below are a number of very simple scripts that you could use to view / add and edit application pools.

Note: Application Pools are only supported on IIS 6 and later.

Enumerating Application Pools

This simple script will simply display the name of each application pool on the local server.

option explicit

dim objAppPools, objAppPool

Set objAppPools = GetObject("IIS://localhost/W3SVC/AppPools")
for each objAppPool in objAppPools
	WScript.echo objAppPool.Name 
next

 

Enumerating Applications in an Application Pool

This script will display the web sites / directories that are using the DefaultAppPool

option explicit

dim Applications, objAppPool, index

Set objAppPool = GetObject("IIS://localhost/W3SVC/AppPools/DefaultAppPool")
WScript.echo objAppPool.Name 

Applications = objAppPool.EnumAppsInPool()
for index = 0 to UBound(Applications)
	WScript.echo "   " & Applications(index)
next

 

Enumerating Application Pool Properties

This script will display all properties of an application pool by looking at the Schema object for an Application Pool.

option explicit

dim Applications, objAppPools, objAppPool, index, IIsSchemaObject
dim PropertyName, IIsAppPoolObject, ValueList

set IIsSchemaObject = GetObject("IIS://localhost/schema/IIsApplicationPool")
set IIsAppPoolObject = GetObject("IIS://localhost/W3SVC/AppPools/DefaultAppPool")

on error resume next

For Each PropertyName In IIsSchemaObject.MandatoryProperties
	WScript.echo PropertyName
next

For Each PropertyName In IIsSchemaObject.OptionalProperties
	WScript.echo PropertyName
	ValueList = IIsAppPoolObject.Get(PropertyName)
	if (isArray(ValueList) = true) then
		for index = lbound(ValueList) to ubound(ValueList)
			WScript.echo " " & index & " - " & ValueList(index)
		next
	else
		WScript.echo " " & ValueList
	end if
next

 

Enumerating the Periodic Recycling of all Application Pools

This script will display the recycling settings of all application pools. You may find that your application stops briefly and that could be caused by the application pool being recycled every 1740 minutes ( every 29 hours) which is the default.

option explicit

dim objAppPools, objAppPool, Schedule

Set objAppPools = GetObject("IIS://localhost/W3SVC/AppPools")
for each objAppPool in objAppPools
	WScript.echo objAppPool.Name
	WScript.echo "  Restart Time           : " & objAppPool.PeriodicRestartTime & " seconds"
	WScript.echo "  Restart Requests       : " & objAppPool.PeriodicRestartRequests
	WScript.echo "  Restart Memory         : " & objAppPool.PeriodicRestartMemory
	WScript.echo "  Restart Private Memory : " & objAppPool.PeriodicRestartPrivateMemory
	WScript.echo "  Restart Requests       : " & objAppPool.PeriodicRestartRequests
	for each Schedule in objAppPool.PeriodicRestartSchedule
		WScript.echo "  Restart At             : " & Schedule
	next
	WScript.echo
next

 

Creating an Application Pool

This script will create a new application pool using the defaults.

strAppPool = "MyAppPool1"
Set objAppPools = GetObject("IIS://localhost/W3SVC/AppPools")
Set objAppPool = objAppPools.Create("IIsApplicationPool", strAppPool)
objAppPool.SetInfo

 

Creating an Application Pool to run with a specific identity

This script will create a new application pool to run as a custom identity. This custom identity could be a local or domain account. You will need to add the user account into the IIS_WPG group on the IIS server. This is because this group has been assigned permissions that the application pool will need to run properly.

strAppPool = "MyAppPool2"
Set objAppPools = GetObject("IIS://localhost/W3SVC/AppPools")
Set objAppPool = objAppPools.Create("IIsApplicationPool", strAppPool)

' 0 = Local System
' 1 = Local Service
' 2 = Network Service
' 3 = Custom Identity -> also set WAMUserName and WAMUserPass
objAppPool.AppPoolIdentityType = 3

' Note: WamUserName must be added to the IIS_WPG group to have correct security rights
objAppPool.WAMUserName = "DOMAIN\Username"
objAppPool.WAMUserPass = "Password"

objAppPool.SetInfo

 

Starting an Application Pool

This script will allow you to start an application pool. You can also specify Stop() and Recycle()  instead of Start().

option explicit

dim objAppPool

Set objAppPool = GetObject("IIS://localhost/W3SVC/AppPools/DefaultAppPool")
objAppPool.Start()

 

Hopefully these simple scripts will show you how easy Application Pools are to create and enumerate.


VBScript - Modified version of Mk3Site.vbs

This script is a modified version of the IIS 5 Mk3Site.vbs script.

I had a request to do some work and the customer would pay me to re-write the script to support some additional features.

I decided to do the work for free and donate the script to the community. It may have some use for some people.

The new features are:

  • Ability to set the application protection to Low, Medium or High
  • Ability to set the Execute options to None, Scripts or Executables
  • Ability to change the log file period
  • Ability to change the log directory

This script was updated from a previously updated script I wrote back in 2001 and is available from www.iisfaq.com

The new features of that script were:

  • Ability to setup URL redirection while creating the site.

 You can download the script from here.

'------------------------------------------------------------------------------------------------
'
' This is a simple script to create a new virtual web server.
'
' Usage: MakeWebSite      <--RootDirectory|-r ROOT DIRECTORY>
'                         <--Comment|-t SERVER COMMENT>
'                         [--computer|-c COMPUTER1[,COMPUTER2...]]
'                         [--HostName|-h HOST NAME[,HOSTNAME2...]]
'                         [--port|-o PORT NUM]
'                         [--IPAddress|-i IP ADDRESS]
'                         [--SiteNumber|-n SITENUMBER]
'                         [--DontStart]
'                         [--verbose|-v]
'                         [--Write]"
'                         [--Execute { NONE, SCRIPTS, EXECUTABLES } ]"
'                         [--AppProtection { LOW, MEDIUM, HIGH } ]"
'                         [--AppName Name]"
'                         [--LogPeriod { DAILY, WEEKLY, MONTHLY, HOURLY} ]"
'                         [--LogFolder LogFileDirectory]"
'                         [--URL Redirectionpath]
'                         [--URLExact]
'                         [--URLChildOnly]
'                         [--URLPermanent]
'                         [--help|-?]
'
' IP ADDRESS            The IP Address to assign to the new server.  Optional.
' HOST NAME             The host name of the web site for host headers.
'      WARNING: Only use Host Name if DNS is set up find the server.
' PORT NUM              The port to which the server should bind
' ROOT DIRECTORY        Full path to the root directory for the new server.
' SERVER COMMENT        The server comment -- this is the name that appers in the MMC.
' SITENUMBER      The Site Number is the number in the path that the web server
'      will be created at.  i.e. w3svc/3
'
' Example 1: MakeWebSite.vbs -r D:\Roots\Company11 --DontStart -t "My Company Site"
' Example 2: MakeWebSite.vbs -r C:\Inetpub\wwwroot -t Test -o 8080
'
'
' Modified by chris crowe - www.iisfaq.com to support multiple host headers and URL Redirection
'------------------------------------------------------------------------------------------------

' Force explicit declaration of all variables
Option Explicit
'On Error Resume Next
Dim ArgIPAddress, ArgRootDirectory, ArgServerComment, ArgSkeletalDir, ArgHostName, ArgPort
Dim ArgComputers, ArgStart
Dim ArgSiteNumber
Dim oArgs, ArgNum
Dim verbose, FSO
' Chris Crowe - blog.crowe.co.nz
dim ArgLogFolder
dim ArgLogFilePeriod
dim ArgAppFriendlyName
dim ArgAppProtection
dim ArgExecute
dim ArgExecuteScripts
dim ArgExecuteExecutables 
dim ArgWrite
const MD_LOGFILE_PERIOD_MAXSIZE = 0 ' Create new log file after reaching maximum size. 
const MD_LOGFILE_PERIOD_DAILY   = 1 ' Create new log file daily. 
const MD_LOGFILE_PERIOD_WEEKLY  = 2 ' Create new log file weekly. 
const MD_LOGFILE_PERIOD_MONTHLY = 3 ' Create new log file monthly. 
const MD_LOGFILE_PERIOD_HOURLY  = 4 ' Create a new log file hourly. 
' Chris Crowe - iisfaq.com
Dim ArgURL, ArgURLExact, ArgURLChildOnly, ArgURLPermanent
ArgIPAddress = ""
ArgHostName = ""
ArgPort = 80
ArgStart = True
ArgComputers = Array(1)
ArgComputers(0) = "LocalHost"
ArgSiteNumber = 0
verbose = false
' Chris Crowe - blog.crowe.co.nz
ArgLogFolder            = ""
ArgLogFilePeriod        = ""
ArgAppFriendlyName      = ""
ArgAppProtection        = 2
ArgExecute              = ""
ArgWrite                = false
' Chris Crowe - iisfaq.com
ArgURL = ""
ArgURLChildonly = false
ArgURLExact = false
ArgURLPermanent = false
Set oArgs = WScript.Arguments
ArgNum = 0
While ArgNum < oArgs.Count
 Select Case LCase(oArgs(ArgNum))
  Case "--port","-o":
   ArgNum = ArgNum + 1
   ArgPort = oArgs(ArgNum) 
  Case "--ipaddress","-i":
   ArgNum = ArgNum + 1
   ArgIPAddress = oArgs(ArgNum)
  Case "--rootdirectory","-r": 
   ArgNum = ArgNum + 1
   ArgRootDirectory = oArgs(ArgNum)
  Case "--comment","-t":
   ArgNum = ArgNum + 1
   ArgServerComment = oArgs(ArgNum)
  Case "--hostname","-h":
   ArgNum = ArgNum + 1
   ArgHostName = oArgs(ArgNum)
  Case "--computer","-c":
   ArgNum = ArgNum + 1
   ArgComputers = Split(oArgs(ArgNum), ",", -1)
  Case "--sitenumber","-n":
   ArgNum = ArgNum + 1
   ArgSiteNumber = CLng(oArgs(ArgNum))
        ' Chris Crowe - blog.crowe.co.nz
  Case "--logfolder": 
   ArgNum = ArgNum + 1
   ArgLogFolder = oArgs(ArgNum)
  Case "--logperiod": 
   ArgNum = ArgNum + 1
   ArgLogFilePeriod = oArgs(ArgNum)
  Case "--appname": 
   ArgNum = ArgNum + 1
   ArgAppFriendlyName = oArgs(ArgNum)
  Case "--appprotection": 
   ArgNum = ArgNum + 1
   ArgAppProtection= oArgs(ArgNum)
  Case "--execute": 
   ArgNum = ArgNum + 1
   ArgExecute = oArgs(ArgNum)
  Case "--write"
   ArgWrite = true
  
  ' Chris Crowe - iisfaq.com
  Case "--url","-u": 
   ArgNum = ArgNum + 1
   ArgURL = oArgs(ArgNum)
  Case "--urlexact"
   ArgURLEXACT = true
  Case "--urlchildonly"
   ArgURLChildOnly = true
  Case "--urlpermanent"
   ArgURLPERMANENT = true
   
  Case "--dontstart":
   ArgStart = False
  Case "--help","-?":
   Call DisplayUsage
  Case "--verbose", "-v":
   verbose = true
  Case Else:
   WScript.Echo "Unknown argument "& oArgs(ArgNum)
   Call DisplayUsage
 End Select 
 ArgNum = ArgNum + 1
Wend
' Chris Crowe - iisfaq.com
If (ArgRootDirectory = "") Then
 WScript.Echo "Missing Root Directory (Required even with URL redirection path)"
 WScript.Echo ""
 Call DisplayUsage
 WScript.Quit(1)
End If
' Check if the root directory exists
Set FSO = WScript.CreateObject("Scripting.FileSystemObject")
  if (FSO.FolderExists(ArgRootDirectory) = False) then
    WScript.echo "The specified root directory does not exist : '" & ArgRootDirectory & "'"
    WScript.Quit(2)
  end if
  
  
  ' Chris Crowe - July 2006
  if (ArgLogFolder > "") then
      if (FSO.FolderExists(ArgLogFolder) = False) then
        WScript.echo "The specified LogFolder directory does not exist : " & ArgLogFolder
        WScript.Quit(2)
      end if
  end if  
  
Set FSO = Nothing

' Chris Crowe - July 2006
if (ArgExecute> "") then
    ArgExecute = ucase(ArgExecute)
    if (ArgExecute = "NONE") then 
        ArgExecuteScripts = false
        ArgExecuteExecutables = false
    elseif (ArgExecute = "SCRIPTS") then 
        ArgExecuteScripts = true
        ArgExecuteExecutables = false
    elseif (ArgExecute = "EXECUTABLES") then 
        ArgExecuteScripts = true
        ArgExecuteExecutables = true
    else
      WScript.echo "The specified Execute value is invalid : " & ArgAppProtection
      WScript.Quit(2)
    end if
end if
if (ArgAppProtection > "") then
    ArgAppProtection = ucase(ArgAppProtection)
    if (ArgAppProtection = "LOW") then ArgAppProtection = 0
    if (ArgAppProtection = "INPROCESS") then ArgAppProtection = 0
    
    if (ArgAppProtection = "HIGH") then ArgAppProtection = 1
    if (ArgAppProtection = "OUTOFPROCESS") then ArgAppProtection = 1
    
    if (ArgAppProtection = "MEDIUM") then ArgAppProtection= 2
    if (ArgAppProtection = "POOLED") then ArgAppProtection = 2
    
    if ((ArgAppProtection = 0) or (ArgAppProtection = 1) or (ArgAppProtection = 2)) then
    else
      WScript.echo "The specified AppProtection value is invalid : " & ArgAppProtection
      WScript.Quit(2)
    end if
end if  
if (ArgLogFilePeriod > "") then
    ArgLogFilePeriod = ucase(ArgLogFilePeriod)
    if (ArgLogFilePeriod = "DAILY") then ArgLogFilePeriod = 1
    if (ArgLogFilePeriod = "WEEKLY") then ArgLogFilePeriod = 2   
    if (ArgLogFilePeriod = "MONTHLY") then ArgLogFilePeriod = 3
    if (ArgLogFilePeriod = "HOURLY") then ArgLogFilePeriod = 4
    
    if ((ArgLogFilePeriod= 0) or (ArgLogFilePeriod= 1) or (ArgLogFilePeriod= 2) or (ArgLogFilePeriod= 3)) then
    else
      WScript.echo "The specified LogFilePeriod is invalid : " & ArgLogFilePeriod
      WScript.Quit(2)
    end if
end if  

If (ArgServerComment = "") Then
 WScript.Echo "Missing Server Comment"
 WScript.Echo ""
 Call DisplayUsage
 WScript.Quit(1)
End If
' end - chris Crowe - iisfaq.com
' chris Crowe - iisfaq.com
Call ASTCreateWebSite(ArgIPAddress, ArgRootDirectory, ArgURL, ArgURLEXACT, ArgURLCHILDONLY, ArgURLPERMANENT, 
ArgServerComment, ArgHostName, ArgPort, ArgComputers, ArgStart) ' chris Crowe - iisfaq.com Sub ASTCreateWebSite(IPAddress, RootDirectory, URL, ArgURLEXACT, ArgURLCHILDONLY, ArgURLPERMANENT,
ServerComment, HostName, PortNum, Computers, Start) Dim w3svc, WebServer, NewWebServer, NewDir, Bindings, BindingString, NewBindings, ComputerIndex
Dim Index, SiteObj, bDone Dim comp, BindingIndex, HostNameINdex, HostNames 'Chris Crowe - www.iisfaq.com Dim URLOPTIONS On Error Resume Next hostNames = Split(HostName,",") For ComputerIndex = 0 To UBound(Computers) comp = Computers(ComputerIndex) If ComputerIndex <> UBound(Computers) Then Trace "Creating web site on " & comp & "." End If ' Grab the web service object Err.Clear Set w3svc = GetObject("IIS://" & comp & "/w3svc") If Err.Number <> 0 Then Display "Unable to open: "&"IIS://" & comp & "/w3svc" End If Trace "Making sure this web server doesn't conflict with another..." For Each WebServer in w3svc If WebServer.Class = "IIsWebServer" Then Bindings = WebServer.ServerBindings For HostNameINdex = 0 To UBound(HostNames) for BindingIndex = 0 to Ubound(Bindings) BindingString = IpAddress & ":" & PortNum & ":" & HostNames(HostNameINdex) If (BindingString = bindings(BindingIndex)) Then Trace "The server bindings you specified are duplicated in another virtual web server." Trace "The Web Server name is [" & WebServer.ServerComment & "], Instance ID [" & WebServer.name & "]" Trace "The Conflicting Bindings are at index [" & bindingIndex & "], [" & bindings(BindingIndex) & "]" WScript.Quit (1) End If next next End If Next Index = 1 bDone = False Trace "Creating new web server..." ' If the user specified a SiteNumber, then use that. Otherwise, ' test successive numbers under w3svc until an unoccupied slot is found If ArgSiteNumber <> 0 Then Set NewWebServer = w3svc.Create("IIsWebServer", ArgSiteNumber) NewWebServer.SetInfo If (Err.Number <> 0) Then WScript.Echo "Couldn't create a web site with the specified number: " & ArgSiteNumber WScript.Quit (1) Else Err.Clear ' Verify that the newly created site can be retrieved Set SiteObj = GetObject("IIS://"&comp&"/w3svc/" & ArgSiteNumber) If (Err.Number = 0) Then bDone = True Trace "Web server created. Path is - "&"IIS://"&comp&"/w3svc/" & ArgSiteNumber Else WScript.Echo "Couldn't create a web site with the specified number: " & ArgSiteNumber WScript.Quit (1) End If End If Else While (Not bDone) Err.Clear Set SiteObj = GetObject("IIS://"&comp&"/w3svc/" & Index) If (Err.Number = 0) Then ' A web server is already defined at this position so increment Index = Index + 1 Else Err.Clear Set NewWebServer = w3svc.Create("IIsWebServer", Index) NewWebServer.SetInfo If (Err.Number <> 0) Then ' If call to Create failed then try the next number Index = Index + 1 Else Err.Clear ' Verify that the newly created site can be retrieved Set SiteObj = GetObject("IIS://"&comp&"/w3svc/" & Index) If (Err.Number = 0) Then bDone = True Trace "Web server created. Path is - "&"IIS://"&comp&"/w3svc/" & Index Else Index = Index + 1 End If End If End If ' sanity check If (Index > 10000) Then Trace "Seem to be unable to create new web server. Server number is "&Index&"." WScript.Quit (1) End If Wend End If on error goto 0 redim NewBindings (ubound(HostNames)) For HostNameINdex = 0 To UBound(HostNames) BindingString = IpAddress & ":" & PortNum & ":" & HostNames(HostNameINdex) Trace "Binding = " & BindingString NewBindings(HostNameINdex) = BindingString next ' Modified by Chris Crowe - July 2006 (Start) if (ArgLogFolder > "") then NewWebServer.LogFileDirectory = ArgLogFolder end if if (ArgLogFilePeriod > "") then NewWebServer.LogFilePeriod = ArgLogFilePeriod end if ' Modified by Chris Crowe - July 2006 (End) NewWebServer.ServerBindings = NewBindings NewWebServer.ServerComment = ServerComment NewWebServer.SetInfo ' Now create the root directory object. Trace "Setting the home directory..." Set NewDir = NewWebServer.Create("IIsWebVirtualDir", "ROOT") NewDir.Path = RootDirectory NewDir.AccessRead = true ' Chris Crowe - July 2006 if (ArgWrite = true) then NewDir.AccessWrite = true end if if (ArgExecute > "") then NewDir.AccessScript = ArgExecuteScripts NewDir.AccessExecute = ArgExecuteExecutables end if ' Modified by Chris crowe - January 2002 if (URL <> "") then trace "Redirection to a URL: " & URL URLOPTIONS= "" if (ArgURLEXACT = true) then URLOPTIONS = ", EXACT_DESTINATION" end if if (ArgURLCHILDONLY = true) then if (URLOPTIONS > "") then URLOPTIONS = URLOPTIONS & ", CHILD_ONLY" else URLOPTIONS = ", CHILD_ONLY" end if end if if (ArgURLPERMANENT = true) then if (URLOPTIONS > "") then URLOPTIONS = URLOPTIONS & ", PERMANENT" else URLOPTIONS = ", PERMANENT" end if end if trace "Redirection Flags : " & URLOPTIONS newDir.httpredirect= URL & URLOPTIONS end if ' Modified by Chris crowe - January 2002 Err.Clear NewDir.SetInfo ' Chris Crowe - July 2006 NewDir.AppCreate2 (ArgAppProtection) if (ArgAppFriendlyName > "") then NewDir.AppFriendlyName = ArgAppFriendlyName NewDir.SetInfo end if If (Err.Number = 0) Then Trace "Home directory set." Else Display "Error setting home directory." End If Trace "Web site created!" If Start = True Then Trace "Attempting to start new web server..." Err.Clear Set NewWebServer = GetObject("IIS://" & comp & "/w3svc/" & Index) NewWebServer.Start If Err.Number <> 0 Then Display "Error starting web server!" Err.Clear Else Trace "Web server started succesfully!" End If End If Next End Sub ' Display the usage message Sub DisplayUsage WScript.Echo "Usage: MakeWebSite <--RootDirectory|-r ROOT DIRECTORY>" WScript.Echo " <--Comment|-t SERVER COMMENT>" WScript.Echo " [--computer|-c COMPUTER1[,COMPUTER2...]]" WScript.Echo " [--port|-o PORT NUM]" WScript.Echo " [--IPAddress|-i IP ADDRESS]" WScript.Echo " [--HostName|-h HOST NAME[,HOSTNAME2...]]" WScript.Echo " [--SiteNumber|-n SITENUMBER]" WScript.Echo " [--AppProtection Level { LOW, MEDIUM, HIGH } ]" WScript.Echo " [--AppName Name]" WScript.Echo " [--Write]" WScript.Echo " [--Execute { NONE, SCRIPTS, EXECUTABLES } ]" WScript.Echo " [--LogPeriod LogFilePeriod { DAILY, WEEKLY, MONTHLY, HOURLY}]" WScript.Echo " [--LogFolder LogFileDirectory]" WScript.Echo " [--URL RedirectionPath]" WScript.Echo " [--URLExact]" WScript.Echo " [--URLChildOnly]" WScript.Echo " [--URLPermanent]" WScript.Echo " [--DontStart]" WScript.Echo " [--verbose|-v]" WScript.Echo " [--help|-?]" WScript.Echo "" WScript.Echo "WARNING: Only use Host Name if DNS is set up find the server." WScript.Echo "" WScript.Echo "Example 1: MakeWebSite.vbs -r D:\Roots\Company11 --DontStart -t ""My Company Site""" WScript.Echo "Example 2: MakeWebSite.vbs -r D:\Roots\Company11 -h ""www.iisfaq.com,www.iis.com"" --DontStart
-t "
"My Company Site""" WScript.Echo "Example 3: MakeWebSite.vbs -r D:\Roots\Company11 -i 192.168.0.1 -t ""My Company Site""
--URL http://www.iisfaq.com --URLExact --URLPermanent"
WScript.Echo "Example 4: MakeWebSite.vbs -r D:\Roots\Company11 --DontStart -t ""My Company Site""
--LogPeriod MONTHLY --LogFolder c:\Root\Company1"
WScript.Echo "Example 5: MakeWebSite.vbs -r D:\Roots\Company11 --DontStart -t ""My Company Site""
--AppName XYZ --LogFolder c:\Root\Company1" WScript.Echo "" WScript.Echo "Note: URLRedirection requires a HTTP:// prefix and a root directory also!" WScript.Echo " Write enables write access to the directory" WScript.Echo "" WScript.Quit (1) End Sub Sub Display(Msg) WScript.Echo Now & ". Error Code: " & Hex(Err) & " - " & err.Description & " - " & Msg End Sub Sub Trace(Msg) if verbose = true then WScript.Echo Now & " : " & Msg end if End Sub

VBScript - How to search all sites and host headers for a particular string of characters?

The following script will allow you to search the local web server for all virtual servers that have been configured for a particular host header value.

The script requires you to specify a value to seach for as a command line parameter.

Example

cscript EnumByHostHeader.vbs SearchString

Where SearchString is some text to search for such as crowe

cscript EnumByHostHeader.vbs crowe

The expected result is something like the following

Searching for CROWE in the host headers

Web Site Instance ID - Server Comment - Host Header
126606719 - photos.crowe.co.nz - PHOTOS.CROWE.CO.NZ
1849151055 - rotties.crowe.co.nz - ROTTIES.CROWE.CO.NZ
2021379493 - Blog (Maintenance) - BLOG.CROWE.CO.NZ
415889539 - fish.crowe.co.nz - FISH.CROWE.CO.NZ


on error resume next
dim Contains
Set ArgObj = WScript.Arguments
If ArgObj.Count < 1 Then
Wscript.echo "Please specify the name or part name to look for in the host header field!"
Wscript.echo ""
Wscript.echo "Example"
Wscript.echo "  cscript EnumByHostHeader.vbs ccrowe"
else
Contains = ucase(ArgObj.Item(0))
dim websrv, site
dim Found
dim webinfo
Found = false
WScript.echo "Searching for " & Contains & " in the host headers"
WScript.echo ""
    WScript.echo "Web Site Instance ID - Server Comment - Host Header"
set websrv = getobject("IIS://Localhost/W3SVC")
if (err <> 0) then
else
  err.Clear
  for each site in websrv
   if (site.classname = "IIsWebServer") then
    bindings = Site.ServerBindings
    For Index = LBound(bindings) To UBound(bindings)
     Values = split(bindings(Index), ":")
     HostHeader = ucase(Values(2))
     if (instr(HostHeader, Contains) > 0) then
      Found = true
      WScript.echo site.Name & " - " & _
                            site.ServerComment & " - " & _
                            HostHeader
     end if
    next
   end if
  next
end if
if (Found = false) then
  WScript.echo "The search term " & Contains & " was not found!"
end if
end if


Some examples of scripting of IIS using ADSI, WMI from VB and C# including the new Microsoft.Web.Administration namespace

Below are some simple examples of how to talk to IIS via ADSI, WMI and the new IIS 7 only .NET Managed Provider.

The IIS ADSI Provider

The IIS ADSI provider exposes COM Automation objects that you can use within command-line scripts, ASP pages, or custom applications to change IIS configuration values stored in the IIS metabase. IIS ADSI objects can be accessed and manipulated by any language that supports automation, such as Microsoft® Visual Basic® Scripting Edition (VBScript), Microsoft JScript®, Perl, Microsoft Active Server Pages (ASP), Visual Basic, Java, or Microsoft C++.

The IIS WMI Provider

Windows Management Instrumentation (WMI) is a technology that allows administrators to programmatically manage and configure the Windows operating system and Windows applications. Beginning with IIS 6.0, IIS includes a WMI provider that exposes programming interfaces that can be used to query and configure the IIS metabase.

The Microsoft.Web.Administration namespace in IIS 7

 This is a new .NET managed namespace that will allow you to talk to IIS 7 and configure all aspects of the server. This API is designed to be simple to code against in an “intellisense-driven” sort of way. At the root level a class called ServerManager exposes all the functionality you will need. At this time it appears that this will not be able to be used from Windows XP but by the time Vista & Windows Server are released this may have been ported to run on a Windows XP client.
 

For more details on these technologies see the following resources:


C# -Using System.DirectoryServices and ADSI

using System;
using System.Collections.Generic;
using System.Text;
// Must be specified and a reference added to System.DirectoryServices
using System.DirectoryServices;

namespace Console_EnumSites_ADSI_CSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            DirectoryEntry entry = new DirectoryEntry("IIS://LocalHost/W3SVC");
            foreach (DirectoryEntry site in entry.Children)
            {
                if (site.SchemaClassName == "IIsWebServer")
                {
                    string ServerComment = site.Properties["ServerComment"].Value.ToString();
                    Console.WriteLine(ServerComment + " (" + site.Name + ")");
                }
            }
        }
    }
}

VB -Using ADSI

on error resume next

dim websrv, site
dim webinfo

set websrv = getobject("IIS://Localhost/W3SVC")
if (err <> 0) then
else
    err.Clear
    for each site in websrv
        if (site.classname = "IIsWebServer") then
            WScript.echo Site.ServerComment & " (" & Site.Name & ")"
        end if
    next
end if

C# -Using System.Managment and WMI

using System;
using System.Collections.Generic;
using System.Text;
using System.Management;

namespace Console_EnumSites_WMI_CSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            ManagementScope oms = new ManagementScope(@"\\.\root\MicrosoftIISv2");
            oms.Connect();

            ObjectQuery oQuery = new ObjectQuery("select * from IISWebServerSetting");
            ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oms, oQuery);
            foreach (ManagementObject oreturn in oSearcher.Get())
            {
                Console.WriteLine(oreturn["ServerComment"]+" ("+oreturn["Name"]+")");
            }
            Console.Read();
        }
    }
}

C# -Using Microsoft.Web.Administration ( II7 Only )

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Web.Administration;

namespace Console_EnumSites
{
    class Program
    {
        static void Main(string[] args)
        {
            ServerManager iisManager = new ServerManager();

            Console.WriteLine("Display IIS Sites in IIS 7");
            Console.WriteLine("".PadLeft(40,'-'));
            foreach(Site site in iisManager.Sites)
            {
                Console.WriteLine("{0} {1}", site.Id.ToString().PadRight(12), site.Name);                
            }
            Console.Read();
        }
    }
}

c# - How to display the HttpExpires property and display its meaning...

The HttpExpires property is documented at the following URL.

http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/3e1d9fbb-6910-4648-a2bb-11a945ca7980.mspx?mfr=true

This simple c# console application will display the settings for the HttpExpires property at the root level of the default web site.

Basically the value is encoded as follows:

  • If the value is a blank string then there is no content expiry.
  • If the value starts with a D, then it is using a dynamic expiration period. This period is appended after the D and is stored as the number of seconds in hexidecimal format.

    Example: “D, 0x15180”    - this 0x15180 is the same as 86,400 seconds or 1 day.
  • If the value starts with an S then the following value is a GMT time of when the expiration will take place.

    Example: “S, Sat, 08 Jul 2006 12:00:00 GMT”

using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;
namespace IISHTTPExpires
{
    class Program
    {
        static void Main(string[] args)
        {         
            Console.WriteLine("IIS HTTP Expires - c#");
            Console.WriteLine();
            // Serve to connect to...
            string ServerName = "LocalHost";
            // Define the path to the metabase
            string MetabasePath = "IIS://" + ServerName + "/W3SVC/1/ROOT";
            try
            {
                // Talk to the IIS Metabase to read the MimeMap Metabase key
                DirectoryEntry Entry = new DirectoryEntry(MetabasePath);
                // Get the Mime Types as a collection
                PropertyValueCollection pvc = Entry.Properties["HTTPExpires"];
                string HttpExpires = pvc.Value.ToString();
                if (HttpExpires.Length == 0)
                {
                    Console.WriteLine("HttpExpires is not enabled!");
                }
                else
                {
                    char HttpExpiresType = HttpExpires[0];
                    switch (HttpExpiresType) { case 'D':
                            string Seconds = HttpExpires.Substring(3);
                            if (Seconds == "0")
                                Seconds = "Immediately";
                            else if (Seconds.StartsWith("0x")==true)
                                Seconds = "in " + int.Parse(HttpExpires.Substring(5),
                                    System.Globalization.NumberStyles.HexNumber).ToString() + " Seconds";
                            else
                                Seconds = "in " + Seconds + " Seconds";
                            Console.WriteLine("HttpExpires {0}", Seconds);
                            break;
                        case 'S':
                            Console.WriteLine("HttpExpires {0}", HttpExpires.Substring(2));
                            break;
                        default:
                            Console.WriteLine("Unknown HttpExpires Type : {0}", HttpExpiresType);
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed to read HttpExpires property with the following exception: \n{0}",
                    ex.Message);
            }
            finally
            {
                Console.Read();
            }
        }
    }
}


c# - How to display the IP Address, TCP/IP Port, and Host Header values from IIS
using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;
namespace EnumSites
{
    class Program
    {
        static void Main(string[] args)
        {
            DirectoryEntry entry = new DirectoryEntry("IIS://localhost/w3svc/1");
            PropertyValueCollection pvc = entry.Properties["ServerBindings"];
            foreach (object value in pvc)
            {
                // Format is IPAddress:Port:HostHeader
                string[] Bits = value.ToString().Split(':');
                string IPAddress = Bits[0];
                string TCPIPPort = Bits[1];
                string HostHeader = Bits[2];
                Console.WriteLine("IP = {0}, Port = {1}, Header = {2}", 
                    (IPAddress.Length == 0) ? "(All Unassigned)" : IPAddress, 
                    TCPIPPort, 
                    (HostHeader.Length == 0) ? "(No Host Header)" : HostHeader);
            }
            Console.Read();
        }
    }
}

This simple code will allow you to display the IP Address, TCP/IP Port, and Host Header values for the default web site. The default web site has an Instance ID of 1.

If you want to display for a different web site then change the "IIS://localhost/w3svc/1" to another instance. You can determine the instance ID from the log file name in the log entry properties dialog in the IIS manager.

 


Christchurch .NET Users Group Meeting - June 21st, 2006

I had the pleasure to present to the Christchurch .NET Users Group ( http://www.dot.net.nz ) last evening. It was a very cold night with hail, sleet, rain and we had around 25 people attend.

I spoke about three topics in my presentation:

IIS Scripting

In the talk on IIS Scripting I discussed the different providers that were available to manage IIS from a command line script or application. These include ADSI and WMI, Admin Base Objects and the new IIS 7 Managed Provider.

References:

IIS Diagnostic Tools

In the discussion about IIS diagnostic tools I presented details on the following tools from the Debug Diagnostic Toolkit for IIS.

Authentication and Access Control Diagnostics

Authentication and Access Control Diagnostics (Authdiag) Version 1.0 allows you to review, test, and correct problems with Internet Information Services (IIS) authentication and authorization. You can use Authdiag to check settings on Web sites, FTP sites, virtual directories, Web directories, and files. Authdiag can help you troubleshoot the following types of issues:

SSL Diagnostics

It provides a centralized location to display all relevant SSL configuration information. Most of this information is stored in the metabase, which is the main IIS configuration file. Information related to certificates is also stored in the Windows registry.

SSL Diagnostics checks for the correct configuration of SSL objects and settings. These include client and server certificates, ports, private keys, and Web site states.

Administrators can test whether their current server certificate is working properly by temporarily replacing the current certificate with a self-signed certificate. Administrators are able to test their certificates with a single click of the mouse.

Administrators can use SSL Diagnostics to quickly simulate the connection, or handshake, between the server and browser, and review the response from the server. This is very helpful for determining where in the SSL handshake process the connection is breaking down.

Debug Diagnostics

Debug Diagnostics (DebugDiag) 1.0 is a comprehensive tool designed to help IIS administrators or developers determine why a IIS worker process is crashing, hanging, or memory leak. It offers a simple User Interface to build rules for capturing these common problems with web applications and also offers a built-in analysis system

References:

IIS7

In the IIS 7 section of the presentation I discussed some of the benefits of the new server and its new modular architecture, new UI, new extensibility, and diagnostics functionality.

I showed a number of demos of IIS 7 including a custom Basic Authentication module, a custom Directory Browsing Module, Tracing Features, Debugging a crashing application pool with Debug Diag and some features of the new User Interface.

References


My presentation was made on the Beta 2 build of Vista Ultimate and most of the tools worked fine on Vista and IIS 7 even though they are not designed to. As far as I know no body left early - a good sign.... IIS can be a dry topic to developers but I hope they learned something useful about the new product and of course scripting and diagnostics that they may not have known previously.


A better registration script for the Atlas Framework for a production server

The following script (taken from http://geekswithblogs.net/colinbo) ( and modified a bit by me ) shows how you can configure your production web sites to support the Atlas Framework.

The original registration script for the http handler only registers the script on the first site (site ID 1 - Default Web Site) where as this script will register it on all sites that do not contain it.

The original script from http://geekswithblogs.net/colinbo also had problems in that:

  1. It did not take any note as to the version of .NET runtime running on the web site!
  2. The original code could not handle an application pool with no Applications assigned to it.

I have fixed them in the following code:

Source Code

Option Explicit
Dim WMIService, ApplicationPool, ApplicationPools, Applications, index, VirtualDirectorySettings
Dim ApplicationName, ScriptMap, FoundMapping, ScriptMapCollection, LastPosition, FrameworkVersion 
Const ComputerName = "localhost"
Const ScriptMapExtension = ".asbx"
Const ScriptMapEntry = ".asbx,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,1,GET,HEAD,POST"
Set WMIService = GetObject("winmgmts:{authenticationLevel=pktPrivacy}\\" + ComputerName + "\root\microsoftiisv2")
Set ApplicationPools = WMIService.ExecQuery("Select * From IIsApplicationPool Where Name LIKE 'W3SVC/AppPools/%'")
For Each ApplicationPool in ApplicationPools
    WScript.Echo "Inspecting Application Pool " + ApplicationPool.Name
    ApplicationPool.EnumAppsInPool Applications
 if (UBound(Applications) > 0) then
     For index = lbound(Applications) to UBound(Applications)
      ApplicationName = CleanApplicationName(Applications(index))
   WScript.echo "Inspecting " +ApplicationName
         Set VirtualDirectorySettings = GetObject( "IIS://" + ComputerName + "/" + ApplicationName)
 
      If Err.number = 0 Then 
          ScriptMapCollection = VirtualDirectorySettings.ScriptMaps 
          FoundMapping = False
    FrameworkVersion  = False
       For Each ScriptMap in ScriptMapCollection      
     if (instr(ScriptMap, "v2.0.50727") <> -1) then FrameworkVersion = true
              If LCase(Left(ScriptMap, Len(ScriptMapExtension))) = ScriptMapExtension then 
                  WScript.Echo ApplicationName + " - Updating (Previous: " + ScriptMap + ")"
               ScriptMap = ScriptMapEntry
            FoundMapping = True
         Exit For
                 End IF
             Next
    If FoundMapping = False and (FrameworkVersion = true) Then
     WScript.Echo "Did not find mapping in " + ApplicationName
     LastPosition = UBound(ScriptMapCollection) + 1
     Redim Preserve ScriptMapCollection(LastPosition)
     WScript.Echo ApplicationName + " - Adding " + ScriptMapExtension
     ScriptMapCollection(LastPosition) = ScriptMapEntry
    End If
    VirtualDirectorySettings.ScriptMaps = ScriptMapCollection
    VirtualDirectorySettings.SetInfo
         Else
          WScript.Echo ApplicationName & " - Unable to locate application virtual directory."
         End If
  Next
 end if
    WScript.Echo 
Next
' Trims the leading /LM/ and trailing /
Function CleanApplicationName(applicationName)
    Dim ReturnValue
    If Len(applicationName) < 5 Then
        WScript.Echo "applicationName should be greater than 5 characters: " + applicationName
        Exit Function
    End If
    ReturnValue = Mid(applicationName, 5)
    ReturnValue = Mid(ReturnValue, 1, Len(ReturnValue) - 1)
    CleanApplicationName = ReturnValue
End Function

For more sample code like this visit : http://geekswithblogs.net/colinbo


C# - How to display MimeMap entries to the console from an instance of IIS

 The following c# application will return all of the MimeMaps defined in an IIS instance. The MimeMaps hold the mime types that IIS uses to return the ContentType header.

An example of such a header is application/octetstream

This example requires a reference to the Active DS IIS Namespace Provider in Visual Studio .NET. This reference enables you to use the IISOle namespace to access the IISMimeType class.

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Specialized;
using System.DirectoryServices;
using System.Collections;
namespace IISMIMEType
{
    class Program
    {
        static void Main(string[] args)
        {
            // Maintain a sorted list to contain the MIME Types
            SortedList sl = new SortedList();
            Console.WriteLine("IIS Mime Map - c#");
            Console.WriteLine();
            // Serve to connect to...
            string ServerName = "LocalHost";
            // Define the path to the metabase
            string MetabasePath = "IIS://" + ServerName + "/MimeMap";
            // Note: This could also be something like
            // string MetabasePath = "IIS://" + ServerName + "/w3svc/1/root";
            try
            {
                // Talk to the IIS Metabase to read the MimeMap Metabase key
                DirectoryEntry MimeMap = new DirectoryEntry(MetabasePath);
                // Get the Mime Types as a collection
                PropertyValueCollection pvc = MimeMap.Properties["MimeMap"];
                // Add each Mime Type so we can display it sorted later
                foreach (object Value in pvc)
                {
                    // Convert to an IISOle.MimeMap - Requires a connection to IISOle
                    // IISOle can be added to the references section in VS.NET by selecting
                    // Add Reference, selecting the COM Tab, and then finding the 
                    // Active DS Namespace provider
                    IISOle.MimeMap mimetypeObj = (IISOle.MimeMap)Value;
                    // Add the mime extension and type to our sorted list.
                    sl.Add(mimetypeObj.Extension, mimetypeObj.MimeType);
                }
                // Render the sorted MIME entries
                if (sl.Count == 0)
                    Console.WriteLine("No MimeMap entries are defined at {0}!", MetabasePath);
                else
                    foreach (string Key in sl.Keys)
                        Console.WriteLine("{0} : {1}", Key.PadRight(20), sl[Key]);
            }
            catch (Exception ex)
            {
                if ("HRESULT 0x80005006" == ex.Message)
                    Console.WriteLine(" Property MimeMap does not exist at {0}", MetabasePath);
                else
                    Console.WriteLine("An exception has occurred: \n{0}", ex.Message);
            }
        }
    }
}
    


Example Output

.*  application/octet-stream
.323  text/h323
.acx  application/internet-property-stream
.ai  application/postscript
.aif  audio/x-aiff
.aifc  audio/aiff
.aiff  audio/aiff
.application  application/x-ms-application
.asf  video/x-ms-asf
.asr  video/x-ms-asf
.asx  video/x-ms-asf
.au  audio/basic
.avi  video/x-msvideo
.axs  application/olescript
.bas  text/plain
.bcpio  application/x-bcpio
.bin  application/octet-stream
.bmp  image/bmp
.c  text/plain
.cat  application/vndms-pkiseccat
.cdf  application/x-cdf
.cer  application/x-x509-ca-cert
.clp  application/x-msclip
.cmx  image/x-cmx
.cod  image/cis-cod
.cpio  application/x-cpio
.crd  application/x-mscardfile
.crl  application/pkix-crl
.crt  application/x-x509-ca-cert
.csh  application/x-csh
.css  text/css
.dcr  application/x-director
.deploy  application/octet-stream
.der  application/x-x509-ca-cert
.dib  image/bmp
.dir  application/x-director
.disco  text/xml
.dll  application/x-msdownload
.doc  application/msword
.dot  application/msword
.dvi  application/x-dvi
.dxr  application/x-director
.eml  message/rfc822
.eps  application/postscript
.etx  text/x-setext
.evy  application/envoy
.exe  application/octet-stream
.fif  application/fractals
.flr  x-world/x-vrml
.gif  image/gif
.gtar  application/x-gtar
.gz  application/x-gzip
.h  text/plain
.hdf  application/x-hdf
.hlp  application/winhlp
.hqx  application/mac-binhex40
.hta  application/hta
.htc  text/x-component
.htm  text/html
.html  text/html
.htt  text/webviewhtml
.ico  image/x-icon
.ief  image/ief
.iii  application/x-iphone
.ins  application/x-internet-signup
.isp  application/x-internet-signup
.IVF  video/x-ivf
.jfif  image/pjpeg
.jpe  image/jpeg
.jpeg  image/jpeg
.jpg  image/jpeg
.js  application/x-javascript
.latex  application/x-latex
.lsf  video/x-la-asf
.lsx  video/x-la-asf
.m13  application/x-msmediaview
.m14  application/x-msmediaview
.m1v  video/mpeg
.m3u  audio/x-mpegurl
.man  application/x-troff-man
.manifest  application/x-ms-manifest
.mdb  application/x-msaccess
.me  application/x-troff-me
.mht  message/rfc822
.mhtml  message/rfc822
.mid  audio/mid
.mmf  application/x-smaf
.mny  application/x-msmoney
.mov  video/quicktime
.movie  video/x-sgi-movie
.mp2  video/mpeg
.mp3  audio/mpeg
.mpa  video/mpeg
.mpe  video/mpeg
.mpeg  video/mpeg
.mpg  video/mpeg
.mpp  application/vnd.ms-project
.mpv2  video/mpeg
.ms  application/x-troff-ms
.mvb  application/x-msmediaview
.nc  application/x-netcdf
.nws  message/rfc822
.oda  application/oda
.ods  application/oleobject
.p10  application/pkcs10
.p12  application/x-pkcs12
.p7b  application/x-pkcs7-certificates
.p7c  application/pkcs7-mime
.p7m  application/pkcs7-mime
.p7r  application/x-pkcs7-certreqresp
.p7s  application/pkcs7-signature
.pbm  image/x-portable-bitmap
.pdf  application/pdf
.pfx  application/x-pkcs12
.pgm  image/x-portable-graymap
.pko  application/vndms-pkipko
.pma  application/x-perfmon
.pmc  application/x-perfmon
.pml  application/x-perfmon
.pmr  application/x-perfmon
.pmw  application/x-perfmon
.png  image/png
.pnm  image/x-portable-anymap
.pnz  image/png
.pot  application/vnd.ms-powerpoint
.ppm  image/x-portable-pixmap
.pps  application/vnd.ms-powerpoint
.ppt  application/vnd.ms-powerpoint
.prf  application/pics-rules
.ps  application/postscript
.pub  application/x-mspublisher
.qt  video/quicktime
.ra  audio/x-pn-realaudio
.ram  audio/x-pn-realaudio
.ras  image/x-cmu-raster
.rgb  image/x-rgb
.rmi  audio/mid
.roff  application/x-troff
.rtf  application/rtf
.rtx  text/richtext
.scd  application/x-msschedule
.sct  text/scriptlet
.setpay  application/set-payment-initiation
.setreg  application/set-registration-initiation
.sh  application/x-sh
.shar  application/x-shar
.sit  application/x-stuffit
.smd  audio/x-smd
.smx  audio/x-smd
.smz  audio/x-smd
.snd  audio/basic
.spc  application/x-pkcs7-certificates
.spl  application/futuresplash
.src  application/x-wais-source
.sst  application/vndms-pkicertstore
.stl  application/vndms-pkistl
.stm  text/html
.sv4cpio  application/x-sv4cpio
.sv4crc  application/x-sv4crc
.t  application/x-troff
.tar  application/x-tar
.tcl  application/x-tcl
.tex  application/x-tex
.texi  application/x-texinfo
.texinfo  application/x-texinfo
.tgz  application/x-compressed
.tif  image/tiff
.tiff  image/tiff
.tr  application/x-troff
.trm  application/x-msterminal
.tsv  text/tab-separated-values
.txt  text/plain
.uls  text/iuls
.ustar  application/x-ustar
.vcf  text/x-vcard
.wav  audio/wav
.wbmp  image/vnd.wap.wbmp
.wcm  application/vnd.ms-works
.wdb  application/vnd.ms-works
.wks  application/vnd.ms-works
.wmf  application/x-msmetafile
.wps  application/vnd.ms-works
.wri  application/x-mswrite
.wrl  x-world/x-vrml
.wrz  x-world/x-vrml
.wsdl  text/xml
.xaf  x-world/x-vrml
.xbm  image/x-xbitmap
.xla  application/vnd.ms-excel
.xlc  application/vnd.ms-excel
.xlm  application/vnd.ms-excel
.xls  application/vnd.ms-excel
.xlt  application/vnd.ms-excel
.xlw  application/vnd.ms-excel
.xml  text/xml
.xof  x-world/x-vrml
.xpm  image/x-xpixmap
.xsd  text/xml
.xsl  text/xml
.xwd  image/x-xwindowdump
.z  application/x-compress
.zip  application/x-zip-compressed
 

For more details on MimeMaps see:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/iissdk/html/b9b7a30c-5d24-4310-bb70-398c3129f6b3.asp

For more details on using System.DirectoryServices to configure IIS see:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/iissdk/html/d39fae66-abe7-4902-a3fc-f36151561f01.asp?frame=true


C# - How to display almost all properties for all IIS Virtual Web Servers

Source Code

Note: You will need to add a reference to System.DirectoryServices if you are using VisualStudio.net

using System;
using System.DirectoryServices;
namespace IISSample
{
    static class Program
    {
        /// 
        /// The main entry point for the application.
        /// 
        [STAThread]
        static void Main()
        {
            const string WebServerSchema = "IIsWebServer"; // Case Sensitive
            string ServerName = "LocalHost";
            DirectoryEntry W3SVC = new DirectoryEntry("IIS://" + ServerName + "/w3svc");
            foreach (DirectoryEntry Site in W3SVC.Children)
            {
                if (Site.SchemaClassName == WebServerSchema)
                {
                    Console.WriteLine("WebSite Instance ID : " +Site.Name);
                    foreach (string PropertyName in Site.Properties.PropertyNames)
                    {
                        Console.WriteLine(PropertyName);
                        PropertyValueCollection pvc = Site.Properties[PropertyName];
                        foreach(object Value in pvc)
                            Console.WriteLine("  " + Value.ToString());
                    }
                }
                Console.WriteLine("".PadRight(80, '-'));
            }
        }
    }
}

Example Output:

ServerSize
  1
NotDeletable
  True
FrontPageWeb
  True
ServerAutoStart
  True
ServerState
  2
ServerComment
  Default Web Site
KeyType
  IIsWebServer
DefaultDoc
  Default.htm,Default.asp,index.htm,iisstart.asp
SecureBindings
  :443:
ServerBindings
  :80:
  :9090:chris
CPUResetInterval
  1440
CPULoggingInterval
  60
CPULoggingOptions
  1
CPULoggingMask
  255
CPUCGIEnabled
  True
CPUAppEnabled
  True
AnonymousPasswordSync
  True
LogType
  1
LogFilePeriod
  1
LogFileTruncateSize
  20971520
LogExtFileFlags
  1414
DirBrowseFlags
  1073741886
CacheISAPI
  True
AllowKeepAlive
  True
CGITimeout
  300
ConnectionTimeout
  900
MaxConnections
  10
ContentIndexed
  True
PasswordChangeFlags
  6
AspLogErrorRequests
  True
AspScriptFileCacheSize
  250
AspScriptEngineCacheMax
  125
AspExceptionCatchEnable
  True
AspTrackThreadingModel
  False
AspAllowOutOfProcComponents
  True
AspEnableAspHtmlFallback
  False
AspEnableChunkedEncoding
  True
AspEnableTypelibCache
  True
AspErrorsToNTLog
  False
AspProcessorThreadMax
  25
AspRequestQueueMax
  3000
AspThreadGateEnabled
  False
AspThreadGateTimeSlice
  1000
AspThreadGateSleepDelay
  100
AspThreadGateSleepMax
  50
AspThreadGateLoadLow
  50
AspThreadGateLoadHigh
  80
AspMaxDiskTemplateCacheFiles
  1000
AspAllowSessionState
  True
AspBufferingOn
  True
AspEnableParentPaths
  True
AspSessionTimeout
  20
AspQueueTimeout
  -1
AspCodepage
  0
AspScriptTimeout
  90
AspScriptErrorSentToBrowser
  True
AppAllowDebugging
  False
AppAllowClientDebug
  False
AspKeepSessionIDSecure
  False
AspBufferingLimit
  134217728
AspEnableApplicationRestart
  True
AspQueueConnectionTestTime
  3
AspSessionMax
  -1
AspLCID
  2048
AspMaxRequestEntityAllowed
  1073741824
AuthFlags
  5
AnonymousUserName
  IUSR_CCROWE
AnonymousUserPass
  O0vqT^=Vz:2\9&
NTAuthenticationProviders
  Negotiate,NTLM
LogPluginClsid
  {FF160663-DE82-11CF-BC0A-00AA006111E0}
Realm
  ap.trimblecorp.net
AspScriptLanguage
  VBScript
AspScriptErrorMessage
  An error occurred on the server when processing the URL.  Please contact the system administrator.
AdminACL
  System.__ComObject
LogFileDirectory
  C:\WINDOWS\system32\LogFiles
AspDiskTemplateCacheDirectory
  %windir%\system32\inetsrv\ASP Compiled Templates
HttpErrors
  400,*,FILE,C:\WINDOWS\help\iisHelp\common\400.htm
  401,1,FILE,C:\WINDOWS\help\iisHelp\common\401-1.htm
  401,2,FILE,C:\WINDOWS\help\iisHelp\common\401-2.htm
  401,3,FILE,C:\WINDOWS\help\iisHelp\common\401-3.htm
  401,4,FILE,C:\WINDOWS\help\iisHelp\common\401-4.htm
  401,5,FILE,C:\WINDOWS\help\iisHelp\common\401-5.htm
  403,1,FILE,C:\WINDOWS\help\iisHelp\common\403-1.htm
  403,2,FILE,C:\WINDOWS\help\iisHelp\common\403-2.htm
  403,3,FILE,C:\WINDOWS\help\iisHelp\common\403-3.htm
  403,4,FILE,C:\WINDOWS\help\iisHelp\common\403-4.htm
  403,5,FILE,C:\WINDOWS\help\iisHelp\common\403-5.htm
  403,6,FILE,C:\WINDOWS\help\iisHelp\common\403-6.htm
  403,7,FILE,C:\WINDOWS\help\iisHelp\common\403-7.htm
  403,8,FILE,C:\WINDOWS\help\iisHelp\common\403-8.htm
  403,9,FILE,C:\WINDOWS\help\iisHelp\common\403-9.htm
  403,10,FILE,C:\WINDOWS\help\iisHelp\common\403-10.htm
  403,11,FILE,C:\WINDOWS\help\iisHelp\common\403-11.htm
  403,12,FILE,C:\WINDOWS\help\iisHelp\common\403-12.htm
  403,13,FILE,C:\WINDOWS\help\iisHelp\common\403-13.htm
  403,15,FILE,C:\WINDOWS\help\iisHelp\common\403-15.htm
  403,16,FILE,C:\WINDOWS\help\iisHelp\common\403-16.htm
  403,17,FILE,C:\WINDOWS\help\iisHelp\common\403-17.htm
  404,*,FILE,C:\WINDOWS\help\iisHelp\common\404b.htm
  405,*,FILE,C:\WINDOWS\help\iisHelp\common\405.htm
  406,*,FILE,C:\WINDOWS\help\iisHelp\common\406.htm
  407,*,FILE,C:\WINDOWS\help\iisHelp\common\407.htm
  412,*,FILE,C:\WINDOWS\help\iisHelp\common\412.htm
  414,*,FILE,C:\WINDOWS\help\iisHelp\common\414.htm
  500,12,FILE,C:\WINDOWS\help\iisHelp\common\500-12.htm
  500,13,FILE,C:\WINDOWS\help\iisHelp\common\500-13.htm
  500,15,FILE,C:\WINDOWS\help\iisHelp\common\500-15.htm
ScriptMaps
  .asp,C:\WINDOWS\system32\inetsrv\asp.dll,5,GET,HEAD,POST,TRACE
  .cer,C:\WINDOWS\system32\inetsrv\asp.dll,5,GET,HEAD,POST,TRACE
  .cdx,C:\WINDOWS\system32\inetsrv\asp.dll,5,GET,HEAD,POST,TRACE
  .asa,C:\WINDOWS\system32\inetsrv\asp.dll,5,GET,HEAD,POST,TRACE
  .idc,C:\WINDOWS\system32\inetsrv\httpodbc.dll,5,OPTIONS,GET,HEAD,POST,PUT,DELETE,TRACE
  .shtm,C:\WINDOWS\system32\inetsrv\ssinc.dll,5,GET,POST
  .shtml,C:\WINDOWS\system32\inetsrv\ssinc.dll,5,GET,POST
  .stm,C:\WINDOWS\system32\inetsrv\ssinc.dll,5,GET,POST
  .asax,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .ascx,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .ashx,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,1,GET,HEAD,POST,DEBUG
  .asmx,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,1,GET,HEAD,POST,DEBUG
  .aspx,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,1,GET,HEAD,POST,DEBUG
  .axd,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,1,GET,HEAD,POST,DEBUG
  .vsdisco,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,1,GET,HEAD,POST,DEBUG
  .rem,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,1,GET,HEAD,POST,DEBUG
  .soap,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,1,GET,HEAD,POST,DEBUG
  .config,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .cs,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .csproj,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .vb,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .vbproj,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .webinfo,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .licx,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .resx,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .resources,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .master,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .skin,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .compiled,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .browser,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .mdb,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .jsl,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .vjsproj,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .sitemap,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .msgx,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,1,GET,HEAD,POST,DEBUG
  .ad,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .dd,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .ldd,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .sd,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .cd,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .adprototype,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .lddprototype,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .sdm,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .sdmDocument,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .ldb,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .svc,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,1,GET,HEAD,POST,DEBUG
  .mdf,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .ldf,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .java,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .exclude,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .refresh,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
HttpCustomHeaders
  X-Powered-By: ASP.NET
MaxBandwidth
  -1

You can also do this for all of the IIS Classes such as:

IIsCertMapper Maps certificates to Windows accounts.
IIsCompressionSchemes Global settings for HTTP 1.1 compression schemes.
IIsCompressionScheme Settings for individual compression schemes.
IIsComputer Establishes global settings for IIS configuration.
IIsCustomLogModule Sets properties for custom logging information field nodes.
IIsFilter Provides information about a specific filter.
IIsFilters Manages filters.
IIsFtpInfo Establishes configuration properties for FTP servers in addition to those set at IIsFtpService.
IIsFtpServer Establishes configuration properties for a single FTP server.
IIsFtpService Establishes configuration properties common to all FTP servers.
IIsFtpVirtualDir Sets properties for an individual FTP virtual directory.
IIsIPSecurity A custom ADSI object you can use to set access permissions by IP address and domain address.
IIsLogModule Contains information about a specific logging module.
IIsLogModules Maintains information about installed logging modules.
IIsMimeMap Manages Multipurpose Internet Mail Extension (MIME) mappings.
IIsMimeType Used to manipulate the list of valid MIME types.
IIsWebDirectory Sets properties for an individual Web directory.
IIsWebFile Sets properties for an individual Web file.
IIsWebInfo Establishes configuration properties for Web servers in addition to those set at IIsWebService.
IIsWebServer Establishes configuration properties for a single Web server.
IIsWebService Establishes configuration properties common to all Web servers.
IIsWebVirtualDir Sets properties for an individual Web virtual directory.

Note: Note all classes are available at all levels in the IIS Metabase Hierarchy - so you can not for example get an IIsVirtualDirectory at the same level as the IIsWebServer because it is a child element of an IIsWebServer

For more details see the following references


Creating a virtual directory using System.EnterpriseServices and C#
I came across this post in the IIS Newsgroups today


I want to create virtual directory in IIS. I have a method in doing C# for doing this . The following code is supposed do my job. But It throws the following errors. I strongly feel there is something going wrong with the metabase path "IIS://localhost/W3SVC/1/Root".

Can somebody help me in finding out correct metabase path.

//Create a virtual directory

System.EnterpriseServices.Internal.IISVirtualRoot vr = new System.EnterpriseServices.Internal.IISVirtualRoot();

string sError;

vr.Create("IIS://localhost/W3SVC/1/Root",@"C:\Demos\WebServices\","WebServices",out sError);

The error it has thrown is :

System.Runtime.InteropServices.COMException (0x80070003): The system cannot find the path specified
at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
at System.DirectoryServices.DirectoryEntry.Bind()
at System.DirectoryServices.DirectoryEntry.get_IsContainer()
at System.DirectoryServices.DirectoryEntries.CheckIsContainer()
at System.DirectoryServices.DirectoryEntries.Add(String name, String schemaClassName)
at System.EnterpriseServices.Internal.IISVirtualRoot.Create(String RootWeb, String inPhysicalDirectory, String VirtualDirectory, String Error)
 

In my search to try to help this person I came across the original location of the code he used at
http://blogs.officezealot.com/charles/archive/2004/10/26/3191.aspx

I never know that there was a System.EnterpriseServices.Internal.IISVirtualRoot object in .NET so I learned something along the way as well.

Note: If testing this you will need to add a reference to System.EnterpriseServices

I did some simple tests to try to reproduce the error that the user has seen. I managed to get the same error by specifying an invalid metabase path which explains the The system cannot find the path specified message.

In the code above the IIS Metabase path is specified as /W3SVC/1/Root. The digit 1 (one) in the code refers to the Web Site with an Instance ID of 1. This is always the default web site.

The way to determine what your web site instance id is; is to look at the log file name.

The Log filename contains a path such as W3SVCx where x is the web site Instance ID.

Open IIS Manager and select the web site.

Right click it and select properties and the following will be displayed.

Click on the properties button to bring up the Extended logging properties dialog.

In the highlighted area in the image above you will see the web site Instance ID.

Replace the number in the code with this number and it should work fine for you.


Windows PowerShell - WMI and IIS

A simple example to return all the fields in the IISWebService object on an IIS 6 computer using Windows PowerShell and the get-wmiobject cmdlet.

A simple example to return just the name fields from the IISWebServer object on an IIS 6 computer.

 


Locating Unused Log File Directories

When running IIS on a server edition you can create multiple web sites and over time you may add and remove sites. When you do this the Log Files are still retained

The following script can be used to find unused log file directories that are no longer associated with any IIS Web Sites - it does not delete them just displays them.

Example Output

Usage

  • cscript LocateUnusedLogFileDirectories.VBS

Source Code

You can download the source code by clicking here.

Option Explicit

dim LogFileDirectory
dim Folders()
dim Sites()
dim Valid()

function EnumerateFolders()
 Dim FSO, Dir, File, Index

 set FSO = createobject("Scripting.FileSystemObject")
 set Dir = fso.GetFolder(LogFileDirectory)

 redim Folders(Dir.SubFolders.Count)
 redim Valid(Dir.SubFolders.Count)

 Index =0

 for each File in Dir.SubFolders
  if (left(File.Name,5) = "W3SVC") then
   Folders(Index) = File.Name
   Valid(Index) = false
   Index = Index+1
  end if
 next

 redim Preserve Folders(Index-1)
 redim Preserve Valid(Index-1)

 set Dir = Nothing
 set FSO = Nothing
end function

function DisplayFolders()
 dim Folder, Index, Bad

 Bad = 0
 for Index= 0 to UBound(Folders)
  if (Valid(Index) = false) then
   Bad = Bad + 1
   WScript.echo LogFileDirectory & "\" & Folders(Index)
  end if
 next
 if (Bad = 0) then
  WScript.echo "There are no Log directories found that are not associated with IIS"
 else
  WScript.echo ""
  WScript.echo Bad & " directories were found..."
 end if
end function

function EnumerateSites()
 Dim IISObj, Web, Index

 Index = 0 
 Set IISOBJ = getObject("IIS://localhost/w3svc")
 for each Web in IISOBJ
  if (Web.Class = "IIsWebServer") then 
    Index = Index + 1
    redim Preserve Sites(Index)
    Sites(Index) = "W3SVC" & Web.Name 
  end if
 next
 Set IISOBj=Nothing
end function

Function ProcessFolders()
 dim Folder, Index, fIndex

 for Index = 0 to UBound(Sites) 
  for fIndex= 0 to UBound(Folders) 
   if (Sites(Index) = Folders(fIndex)) then
    Valid(fIndex) = true
   end if
  next
 next
end Function

function GetDefaultLogFolderPath
 Dim IISObj

 Set IISOBJ = getObject("IIS://localhost/w3svc")
 LogFileDirectory =  IISObj.LogFileDirectory
 Set IISOBj = Nothing
end function

function WriteHeader
 WScript.Echo "The following directories are no longer associated with any IIS Web Sites."
 WScript.Echo ""
end function

call WriteHeader
call GetDefaultLogFolderPath
call EnumerateFolders
call EnumerateSites
call ProcessFolders
call DisplayFolders

How to enumerate the Windows NT Services and if they are running from an ASP script.

The following ASP script will allow you to view all services on a particular computer and their current state (Started, Stopped, Starting, Stopping etc)

Important

By default you will not be able to run the script because the IUSR_ computer account does not have the correct permissions to perform this action.

If you do try to run this script with the standard IUSR_ account you will get the following error.

HTTP 500.100 - Internal Server Error - ASP error
Internet Information Services


Technical Information (for support personnel)

  • Error Type:
    (0x80041003)
    /service/Default.asp, line 4
     
  • Page:
    GET /service/Default.asp

 

Line 4 was this line in the source file: set objService = GetObject("winmgmts:")

The way I worked around this was to create a new local account on the IIS server (in my case Windows XP) called "MyASPService". I gave this account no special permissions or anything else just created the new account.

You then create a new directory in your web site called "MyServices" or what ever name you want.

In the Internet Information Server manager you then configure this directory by changing the default anonymous user account from the IUSR_ account to your new "MyASPService" account as shown below.

When you now request the page in the browser it will now use the new MyASPService account and it will work.

Example Outputt

The Dhcp service is Running
Service Name Service Caption Service State
Adobe LM Service Adobe LM Service Stopped
Alerter Alerter Stopped
ALG Application Layer Gateway Service Running
AppMgmt Application Management Stopped
aspnet_state ASP.NET State Service Stopped
AudioSrv Windows Audio Running
BITS Background Intelligent Transfer Service Stopped
Browser Computer Browser Running
CacheMgr Sophos Cache Manager Running
CiSvc Indexing Service Stopped
ClipSrv ClipBook Stopped
clr_optimization_v2.0.50215_32 .NET Runtime Optimization Service v2.0.50215_X86 Stopped
clr_optimization_v2.0.50727_32 .NET Runtime Optimization Service v2.0.50727_X86 Stopped
COMSysApp COM+ System Application Running
<%
set objService = GetObject("winmgmts:")

' To query a specific service
servicename = "Dhcp"
set service = objService.Get("Win32_Service.Name='" & servicename & "'")
Response.Write "The " & ServiceName & " service is " & service.state & "
"


' To enumerate all services
Response.Write ""
Response.Write""
Response.Write""
Response.Write""
Response.Write""
Response.Write""
foreachServiceinobjService.InstancesOf("Win32_Service")
Response.Write""
Response.Write""
Response.Write""
Response.Write""
Response.Write""
Next
Response.Write"
Service Name Service Caption Service State
" & service.name & " " & service.Caption & " " & service.state & "
"

%><html>
<body>
<%
set objService = GetObject("winmgmts:")

' To query a specific service
servicename = "Dhcp"
set service = objService.Get("Win32_Service.Name='" & servicename & "'")
Response.Write "The " & ServiceName & " service is " & service.state & "<hr>"

' To enumerate all services
Response.Write "<table>"
Response.Write "<TR>"
Response.Write "<TH>Service Name</TH>"
Response.Write "<TH>Service Caption</TH>"
Response.Write "<TH>Service State</TH>"
Response.Write "</TR>"
for each Service in objService.InstancesOf("Win32_Service")
  Response.Write "<TR>"
  Response.Write "<TD>" & service.name & "</TD>"
  Response.Write "<TD>" & service.Caption & "</TD>"
  Response.Write "<TD>" & service.state & "</TD>"
  Response.Write "</TR>"
Next
Response.Write "</table>"

%>
</body>
</html>

Simple VB Script to show the authentication methods enabled for directories in a web site.

The following script will allow you to process all physcial and virtual directories for a particular web site and show what authentication methods are enabled.

Each directory will have one or more of the following to determine the authentication methods enabled.

  • A = Anonymous
  • B = Basic
  • D = Digest
  • N = NTLM
  • S = SSL
  • S128 = SSL 128 Bit

You must specify the web site instance id when calling the script. In the case of Windows XP Pro there is (by default) only one web site which has an instance ID of 1. If you are running multiple web sites on a Server OS or you have created multiple web sites on XP pro then you can find the web site instance ID by the following method.

  • Right click the web site, select properties, on the web site tab under logging click the Properties button, part of the log file name will contain the web site #

    example log filename: W3SVC1\exyymmdd.log  - the web site is 1
                                     W3SVC45\exyymmdd.log - the web site is 45

Calling Usage:   cscript EnumAuthenticationMethods.vbs  InstanceID

Example Output

You can download the source for this script here (just rename to .VBS from the .TXT file that it is now)

function EnumVirtualDirectories(LevelMachineNameObjectPathDirStyle)
  Dim ChildObjectIISObkect

  on error resume next
  Err.Clear

  IIsObjectPath = "IIS://" & MachineName
  If (ObjectPath = ""Then
    exit function
  else
    IIsObjectPath = IIsObjectPath & "/" & ObjectPath
  End If

  'WScript.Echo "Checking : " & IISObjectPath

  Set IIsObject = GetObject(IIsObjectPath)

  If (Err.Number <> 0Then
    if (Level = 1then
      WScript.Echo "Error: " & Err.Description & " (" & Err.Number & ")"
    end if
    exit function
  End If

  Err.Clear

  For Each ChildObject In IIsObject
    If (Err.Number <> 0Then
      '    WScript.Echo "Error = " & Err.Description
      '      Exit For
    end if

    if (ChildObject.Class = DirStylethen
      ChildObjectName = Right(ChildObject.AdsPathLen(ChildObject.AdsPath- 6)
      ChildObjectName = Right(ChildObjectNameLen(ChildObjectName- InStr(ChildObjectName"/") )

      if (len(ChildObjectName< 60then
        ChildObjectName = ChildObjectName & space(60-len(childObjectName))
      end if

      Annonymous  = " "
      Basic    = " "
      Digest    = " "
      NTLM    = " "
      SSL      = " "
      SSL128    = " "

      if (ChildObject.AuthAnonymousthen Annonymous = "A"
      if (ChildObject.AuthBasicthen Basic = "B"
      if (ChildObject.AuthDigestthen Digest = "D"
      if (ChildObject.AuthNTLMthen NTLM = "N"

      if (ChildObject.AccessSSLthen SSL = "S"
      if (ChildObject.AccessSSL128then SSL128 = "128"

      WScript.Echo ChildObjectName & " " & Annonymous & " " & Basic & " " & Digest & " " & _
          NTLM & " " & SSL & SSL128

      EnumVirtualDirectories Level+1MachineName,  ChildObjectNameDirStyle
    end if
  next

End Function

Sub DisplayHelpMessage()
  WScript.Echo
  WScript.Echo "Usage:"
  WScript.Echo "      EnumAuthenticationMethods.VBS WebSiteNumber"
  WScript.Echo
  WScript.Echo "WebSiteNumber is the number of the web site, you have two methods to determine this:"
  WScript.Echo
  WScript.Echo "#1 = Run FINDWEB.VBS"
  WScript.Echo "#2 = Right click the web site, select properties, on the web site tab"
  WScript.Echo "     under logging click the Properties button, part of the log file"
  WScript.Echo "     name will contain the web site #"
  WScript.Echo
  WScript.Echo "     example log filename: W3SVC1\exyymmdd.log  - the web site is 1"
  WScript.Echo "                           W3SVC45\exyymmdd.log - the web site is 45"
end sub

Const GENERAL_FAILURE = 2

' Get the Arguments object
Set ArgObj = WScript.Arguments

' Test to make sure there is at least one command line arg - the command
If ArgObj.Count < 1 Then
  DisplayHelpMessage
  WScript.Quit (GENERAL_FAILURE)
End If

Servername = "LocalHost"
WebSiteID    = ArgObj(0)
WebSite        = "W3SVC/" & WebSiteID & "/Root"
Level             = 1

WScript.Echo "Authentication Methods:"
WScript.Echo "    A=Anonymous, B=Basic, D=Digest, N=NTLM, S=SSL, S128=SSL 128bit"
WScript.Echo ""
WScript.Echo "Virtual Directories for " & WebSite
EnumVirtualDirectories LevelServerNameWebSite"IIsWebVirtualDir"

WScript.Echo ""
WScript.Echo "Physical Directories for " & WebSite
EnumVirtualDirectories LevelServerNameWebSite"IIsWebDirectory"


Simple VB Script to show what directories allow anonymous access or not for a web site.

I saw a request on the Microsoft.Public.InetServer.IIS newsgroup today and so I modified a prevously written script I wrote on www.iisfaq.com to do the task.

Question

  • I'm running an IIS 5.1 web server at home (Windows XP Pro), and what I was hoping to do is list all of the directories for a web site which have anonymous access disabled

Answer

The following script will allow you to process all physcial and virtual directories for a particular web site and show if they allow anonymous access or not.

You must specify the web site instance id.

In the case of Windows XP Pro there is (by default) only one web site which has an instance ID of 1.

If you are running multiple web sites on a Server OS or you have created multiple web sites on XP pro then you can find the web site instance ID by the following method.

  • Right click the web site, select properties, on the web site tab under logging click the Properties button, part of the log file name will contain the web site #

    example log filename: W3SVC1\exyymmdd.log  - the web site is 1
                                     W3SVC45\exyymmdd.log - the web site is 45

Calling Usage:   cscript EnumAnonymousAccessDiabled.vbs  InstanceID

Example Output

You can download the source for this script here (just rename to .VBS from the .TXT file that it is now)

function EnumVirtualDirectories(LevelMachineNameObjectPathDirStyle)
  Dim ChildObjectIISObkect

  on error resume next
  Err.Clear

  IIsObjectPath = "IIS://" & MachineName
  If (ObjectPath = ""Then
    exit function
  else
    IIsObjectPath = IIsObjectPath & "/" & ObjectPath
  End If

  'WScript.Echo "Checking : " & IISObjectPath

  Set IIsObject = GetObject(IIsObjectPath)

  If (Err.Number <> 0Then
    if (Level = 1then
      WScript.Echo "Error: " & Err.Description & " (" & Err.Number & ")"
    end if
    exit function
  End If

  Err.Clear

  For Each ChildObject In IIsObject
    If (Err.Number <> 0Then
      '    WScript.Echo "Error = " & Err.Description
      '      Exit For
    end if

    if (ChildObject.Class = DirStylethen
      ChildObjectName = Right(ChildObject.AdsPathLen(ChildObject.AdsPath- 6)
      ChildObjectName = Right(ChildObjectNameLen(ChildObjectName- InStr(ChildObjectName"/") )

      if (len(ChildObjectName< 60then
        ChildObjectName = ChildObjectName & space(60-len(childObjectName))
      end if
      WScript.Echo ChildObjectName & " - " & ChildObject.AuthAnonymous

      EnumVirtualDirectories Level+1MachineName,  ChildObjectNameDirStyle
    end if
  next

End Function

Sub DisplayHelpMessage()
  WScript.Echo
  WScript.Echo "Usage:"
  WScript.Echo "      EnumAnonymousAccessDisabled.VBS WebSiteNumber"
  WScript.Echo
  WScript.Echo "WebSiteNumber is the number of the web site, you have two methods to determine this:"
  WScript.Echo
  WScript.Echo "#1 = Run FINDWEB.VBS"
  WScript.Echo "#2 = Right click the web site, select properties, on the web site tab"
  WScript.Echo "     under logging click the Properties button, part of the log file"
  WScript.Echo "     name will contain the web site #"
  WScript.Echo
  WScript.Echo "     example log filename: W3SVC1\exyymmdd.log  - the web site is 1"
  WScript.Echo "                           W3SVC45\exyymmdd.log - the web site is 45"
end sub

Const GENERAL_FAILURE = 2

' Get the Arguments object
Set ArgObj = WScript.Arguments

' Test to make sure there is at least one command line arg - the command
If ArgObj.Count < 1 Then
  DisplayHelpMessage
  WScript.Quit (GENERAL_FAILURE)
End If

Servername = "LocalHost"
WebSiteID    = ArgObj(0)
WebSite        = "W3SVC/" & WebSiteID & "/Root"
Level             = 1

WScript.Echo "Allow Anonymous Access"
WScript.Echo ""
WScript.Echo "Virtual Directories for " & WebSite
EnumVirtualDirectories LevelServerNameWebSite"IIsWebVirtualDir"

WScript.Echo ""
WScript.Echo "Physical Directories for " & WebSite
EnumVirtualDirectories LevelServerNameWebSite"IIsWebDirectory"

Display a list of all sites on the local IIS server and the bindings (IP Address, TCP/IP Port, Host Header) that they have.

This script will show you each Web Site ID and the description and the bindings that they are using.

Save the script to a file with a .VBS file extension and then run using this command:

cscript  MyFile.VBS

MachineName = "localhost"
IIsObjectPath = "IIS://" & MachineName & "/w3svc"


Set IIsObject = GetObject(IIsObjectPath)
for each obj in IISObject
if (Obj.Class = "IIsWebServer") then
BindingPath = IIsObjectPath & "/" & Obj.Name

Set IIsObjectIP = GetObject(BindingPath)
wScript.Echo IISObjectIP.ServerComment & " ( W3SVC" & obj.Name & " ) "

ValueList = IISObjectIP.Get("ServerBindings")
ValueString = ""
For ValueIndex = 0 To UBound(ValueList)
value = ValueList(ValueIndex)
Values = split(value, ":")
IP = values(0)
if (IP = "") then
IP = "(All Unassigned)"
end if
TCP = values(1)
if (TCP = "") then
TCP = "80"
end if
HostHeader = values(2)

if (HostHeader <> "") then
wScript.Echo " IP = " & IP & " TCP/IP Port = " & TCP & ", HostHeader = " & HostHeader
else
wScript.Echo " IP = " & IP & " TCP/IP Port = " & TCP
end if
Next
wScript.Echo ""
set IISObjectIP = Nothing
end if
next
set IISObject = Nothing

Example Output

Default Web Site ( W3SVC1 )
IP = 10.1.1.11 TCP/IP Port = 80

WebSite1 ( W3SVC1036328378 )
IP = 10.1.1.74 TCP/IP Port = 80

WebSite2 ( W3SVC1816184000 )
IP = 10.1.1.73 TCP/IP Port = 80

WebSite3 ( W3SVC1867813904 )
IP = 10.1.1.72 TCP/IP Port = 80

WebSite4 ( W3SVC568530179 )
IP = 10.1.1.71 TCP/IP Port = 80

WebSite5 ( W3SVC719499532 )
IP = 10.1.1.70 TCP/IP Port = 80

WebSite6 ( W3SVC669732006 )
IP = (All Unassigned) TCP/IP Port = 81
 

 


Displaying the Web Site ID and the Description

This script will show you the W3SVC Web Site ID and the description.

With IIS 6 the Web Site ID is a randomly generated number for each site that is created other than the Default Web Site which has an Web Site ID of 1)

For example:

W3SVC1
W3SVC719499532
W3SVC383732556

Knowing which web site these being to is a problem as it requires you to manually look at each web site. The following script will allow you to output the ID and name.

Save the script to a file with a .VBS file extension and then run using this command:

cscript  MyFile.VBS

Function ProcessWebSite(ServiceType, SiteNumber)
Set IISWebSite = getObject("IIS://localhost/" & ServiceType & "/" & SiteNumber)
Set IISWebSiteRoot = getObject("IIS://localhost/" & ServiceType & "/" & SiteNumber & "/root")
ProcessWebSite = IISWebSite.ServerComment
Set IISWebSiteRoot = nothing
Set IISWebSite = Nothing
end function

Function ShowSites(ServiceType, ClassName, Title)
Wscript.echo "Web Sites Description"
Wscript.echo "==============================================================="
Set IISOBJ = getObject("IIS://localhost/" & ServiceType)
for each Web in IISOBJ
if (Web.Class = ClassName) then
wscript.echo Ucase(ServiceType) & "/" & Web.Name & _
Space(17-(len(Ucase(ServiceType))+1+len(Web.Name))) & " " & _
ProcessWebSite(ServiceType, Web.name)
end if
next
Set IISOBj=Nothing
WScript.Echo ""
End function

Call ShowSites("w3svc", "IIsWebServer", "Web")

The output from this is similar to the following:

Web Sites                    Description
===============================================================
W3SVC/1                   Default Web Site
W3SVC/1036328378 WebSite1
W3SVC/1816184000 WebSite2
W3SVC/1867813904 WebSite3
W3SVC/568530179   WebSite4
W3SVC/719499532   WebSite5
W3SVC/669732006   WebSite6

Microsoft Scripting Resources

I came across a number of cool scripting utilities today that may help others; these are:

  • Do-It-Yourself Script Center Kit
  • Scriptomatic 2.0
  • TechNet Script Center Sample Scripts
  • WMI Code Creator v1.0
  • HTA Helpomatic
  • TechNet Script Center Sample Scripts
  • Technet Script Center
  • ADSI Scriptomatic
  • Tweakomatic

Do-It-Yourself Script Center Kit

The Do-It-Yourself Script Center Kit includes all the materials you need to create your own version of the TechNet Script Center, either as stand-alone Web pages, stand-alone .vbs files, or as a .chm Help file. Included in the Kit are a database ( Microsoft Access ) of all the scripts found in the TechNet Script Center Script Repository as of January 2005, as well helper scripts for creating Web pages, .vbs files, and .chm files.

The Kit also includes instructions for using these helper scripts.

For more details see:
http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=D187C9D7-FFA8-49CD-BB33-363DB8FA481E&sGuid=8c9e492e-9f9b-4f33-8bad-26c69ee9a42b&hash=P8DMHJ

Scriptomatic 2.0

A completely new version of the famous Scriptomatic, the utility that writes WMI scripts for you. (And, in the process, teaches you the fundamental concepts behind writing WMI scripts for yourself.) U

nlike its predecessor, Scriptomatic 2.0 isn’t limited to writing just VBScript scripts; instead, Scriptomatic 2.0 can write scripts in Perl, Python, or JScript as well.

In addition, Scriptomatic 2.0 gives you a host of new output formats to use when running scripts, including saving data as plain-text, as a stand-alone Web page, or even as XML.

Scriptomatic 2.0 handles arrays, it converts dates to a more readable format, and it works with all the WMI classes on your computer; on top of all that, it also writes scripts that can be run against multiple machines.

For more details see:
http://www.microsoft.com/downloads/details.aspx?familyid=09DFC342-648B-4119-B7EB-783B0F7D1178&displaylang=en

Incase you want the old 2002 version :
http://www.microsoft.com/downloads/details.aspx?familyid=9EF05CBD-C1C5-41E7-9DA8-212C414A7AB0&displaylang=en

TechNet Script Center Sample Scripts

Sample scripts found in the TechNet Script Center. The sample scripts are not supported under any Microsoft standard support program or service. You can, however, report issues and bugs by sending e-mail to scripter@microsoft.com.
 

HTA Helpomatic

The HTA Helpomatic is a utility that helps script writers create HTML Applications (HTAs). HTAs enable you to provide a graphical user interface for your scripts, an interface that can include anything from list boxes to radio buttons to checkboxes. The HTA Helpomatic includes sample VBScript code and sample HTML code showing you how to do things like add a button to an HTA. Equally important, the Helpomatic also shows you how you can run a script any time that button is clicked. As an added bonus, the Helpomatic enables you to modify the scripts and HTML code and test those modifications in the utility itself.

For more details see:
http://www.microsoft.com/downloads/details.aspx?familyid=231D8143-F21B-4707-B583-AE7B9152E6D9&displaylang=en

WMI Code Creator v1.0
The WMI Code Creator tool generates code that uses WMI to obtain management information or perform management tasks. You can use the tool to learn how to manage computers using WMI scripting and WMI .NET. The tool generates code that runs on the local computer, a remote computer, or a group of remote computers based on your selection from the Target Computer menu on the tool. You can also execute the generated code directly from the tool.

The tool is meant to help IT Professionals quickly create management scripts and to help developers learn WMI scripting and WMI .NET. The tool helps take the complexity out of writing code that uses WMI and helps developers and IT Professionals understand how powerful and useful WMI can be for managing computers.

Using the tool, you can query for management information such as the name and version of an operating system, how much free disk space is on a hard drive, or the state of a service. You can also use the tool to execute a method from a WMI class to perform a management task. For example, you can create code that executes the Create method of the Win32_Process class to create a new process such as Notepad or another executable. The tool also allows you to generate code to receive event notifications using WMI. For example, you can select to receive an event every time a process is started or stopped, or when a computer shuts down.

The tool also allows you to browse through the available WMI namespaces and classes on the local computer to find their descriptions, properties, methods, and qualifiers.

The code that creates the tool is also included in the download. The tool was created using WMI .NET, and the code for the tool can help developers understand how WMI .NET is used to create applications and manage information. Be sure to read the end-user license agreement that is included in the download.
 
For more details see:
 
Technet Script Center
The TechNet script center is a repositaty specially tailed for scripting, there are columns and verything you need to learn how to write scripts for Windows is right there!
 
Find articles, documentation, webcasts, and even hands-on labs for all levels, right at your fingertips.
 
 
ADSI Scripomatic
The ADSI Scriptomatic is designed to help you write ADSI scripts; that is, scripts that can be used to manage Active Directory or IIS.
 
The ADSI Scriptomatic also teaches you an important point about ADSI scripting: like WMI, there are consistent patterns to ADSI scripts.
 
For example, the ADSI Scriptomatic will help you write a script to delete a user account. It will also help you write scripts for deleting groups and organizational units.
 
And if you take a close look at the scripts for deleting different objects, you’ll see something very interesting: theyre practical identical!
 
 
Tweakomatic

Tweakomatic is a nifty new utility that writes scripts that enable you to retrieve and/or configure Windows and Internet Explorer settings. So what, you might say. Well, think about it. Because these are Windows Management Instrumentation (WMI) scripts, they can be used to configure settings on remote computers. Need to change something on a remote computer? Then haul out Tweakomatic. And think about this: because Tweakomatic writes scripts, you could do something like run these scripts as logon or logoff scripts. In other words, you could quickly, easily, and automatically configure settings on any or all the computers in your organization. Tweakomatic is undoubtedly the single best thing Microsoft has released since Windows itself

For more details see:
http://www.microsoft.com/technet/scriptcenter/tools/twkmatic.mspx


IIS Diagnostics Kits

The IIS Diagnostics Toolkit is a combined release of popular tools used by today's IIS users. These tools include tools aimed at resolving problems related to Secure Socket Layer (SSL) issues, permission or security problems, gathering data for your SMTP server included with IIS, as well as the famous Log Parser utility used to sift through hundreds or thousands of log files very quickly.

The toolkit consolidates all the tools into a convienant download and is supplemented by updates every 90-days to ensure that users have the most current diagnostics tools at their fingertips.

For more details see:
http://www.microsoft.com/downloads/details.aspx?FamilyID=9bfa49bc-376b-4a54-95aa-73c9156706e7&DisplayLang=en


Authentication and Access Control Diagnostics 1.0 (more commonly known as AuthDiag) is a tool released by Microsoft aimed at aiding IT professionals and developers at more effectively finding the source of authentication and authorization failures.

These users have often seen behavior from Internet Information Services (IIS) that doesn't seem appropriate or random when users authenticate to the IIS server. The complex world of authentication types and the various levels of security permissions necessary to allow a user to access the server causes many hours of labor for those tasked with troubleshooting these problems.

AuthDiag 1.0 offers a robust tool that offers a efficient method for troubleshooting authentication on IIS 5.x and 6.0. It will analyze metabase configuration and system-wide policies and warn users of possible points of failure and guide them to resolving the problem. AuthDiag 1.0 also includes a robust monitoring tool called AuthMon designed at capturing a snapshot of the problem while it occurs in real-time. AuthMon is robust and specially designed for IIS servers removing any information not pertinent to the authentication or authorization process.

For more details see:
http://www.microsoft.com/downloads/details.aspx?FamilyID=e90fe777-4a21-4066-bd22-b931f7572e9a&DisplayLang=en


A common problem for administrators of IIS servers is configuring and troubleshooting SSL enabled websites. To assist in administrators efforts, Microsoft has designed a tool - SSL Diagnostics - to aid in quickly identifying configuration problems in the IIS metabase, certificates, or certificate stores.

This tool allows users to review configuration information in a easy to read view mode or to run the tool silently with only the creation of a log file. During use, administrators can simulate the SSL handshake to find errors. They can also quickly "hot swap" certificates for testing purposes.

These packages come in two forms: Express and Full. The express will only give the pertinent tools for administrators to use SSL Diagnostics while full install installs the same files with the appropriate documentation. Included in the full install is a SSL Frequently Asked Questions that can assist in the learning of SSL for administrators

For more details see:
http://www.microsoft.com/downloads/details.aspx?FamilyID=cabea1d0-5a10-41bc-83d4-06c814265282&DisplayLang=en


The IIS 6.0 Resource Kit Tools can help you administer, secure, and manage IIS. Use them to query log files, deploy SSL certificates, employ custom site authentication, verify permissions, troubleshoot problems, migrate your server, run stress tests, and more.

The following tools are available in this package:

  • IIS 6.0 Migration Tool Version 1.0 Version 1.1 Now Available!
  • Apache to IIS 6.0 Migration Tool Version 1.0
  • CustomAuth Version 1.0
  • IISCertDeploy.vbs Version 1.0
  • IIS Host Helper Service Version 1.0
  • IISState Version 3.0
  • Log Parser Version 2.1 Version 2.2 Now Available!
  • Metabase Explorer Version 1.6
  • Permissions Verifier Version 1.0
  • RemapUrl Version 1.0
  • SelfSSL Version 1.0
  • TinyGet Version 5.2
  • Web Capacity Analysis Tool Version 5.2
  • WFetch Version 1.3

For more details see:
http://www.microsoft.com/downloads/details.aspx?FamilyID=56fc92ee-a71a-4c73-b628-ade629c89499&DisplayLang=en


IIS - Scripts for managing Internet Information Server
 

If you are looking to manage IIS using scripts instead of having to use the GUI the following resources may be helpful to you.

Scripts hosted on www.iisfaq.com - written mostly by me in VBScript using ADSI for IIS 4+

Backup and Restore

How do I backup the Metabase using a script?
How to get a listing of all the Metabase backups that have been made?

Content Indexing

Enum if a web site folders are enabled/disabled for content indexing

Custom Headers

How to add an entry to the CustomHeaders?
How to view the CustomHeaders defined for a specific web site?

FTP

How can I get a simple listing of the FTP Sites on my Web Server
How do I add a new FTP site using ADSI?
How to find the default logon domain for an FTP site?
How to set the default logon domain for an FTP Site?
Is there a way to force the FTP filenames to appear in lowercase?
makeFTPDirsFromTextFile.vbs

IP Address

Changing the IP Address of a large number of Web Sites which are configured using Host Headers
How can I change the IP Address on a particular web site?
How can I export my list of IP And Domain name restrictions from a website?
How can I set 2000 IP address and domain name restrictions?
How do I add multiple IP Addreses to my Web Site?
How do I list all the web sites and the IP addresses associated with each web site?
I get a message "A duplicate name exists on the network" how do I find what site is the duplicate?
I have 100 IP Addresses and would like a script to tell me which IP address to use next.
I have about 50 websites on a NT 4 server that I need to change the IPaddress for each due to IP address changes.

ISAPI Filters

How do I add an ISAPI filter to my Web Site using a Script?
How do I know what custom ISAPI filters are defined on my Web Sites?
More details on ISAPI Extensions and Filters

 Log Files

How can I delete all files from my IIS log file directory that are over 90 days old?
How can I find out all the log options that have been set?
How can I find out what files are in my IIS log directory for a particular web site?
How can I get a listing of all the log file directories and if they exist or not?
How can I set the Log File Directory?
How do I find all the available web site logging formats available?
I have a lot of log files on my system how can I archive them easily?
I see how to change, read, write browse in the directory tab, but I can't find anything about the 'Index this resource' box?
This script will export relevant IIS settings to a log file that you can import into MSAccess or MS Excel.

MIMEMAP

How can I add an entry to the MIMEMAP?
How can I delete an entry from the MIMEMAP?
How can I disable caching of specific file types?
How can I display the items in the MIMEMAP?

Misc Scripts

Do do I add or remove a Script Mapping?
How can I determine from within my script if IIS is version 4 or Version 5?
How can I determine if a web site or virtual directory points to a specific physical path?
How can I enable pass through authentification on IIS5?
How can I find all the properties available for an IIS ADSI object?
How can I set the application protection level - such as Low (InProcess), Medium (Pooled) or High (Out Of Process)?
How do I find all the invalid paths in my web server?
How do I read a web page from the server and then show it to the user?

Passwords and Authentication

How can I find out the password for the IUSR_Computername account?

Scripting DNS Zones and Resource Records

HowTo: Scripting DNS entries in Windows 2000

SMTP

How can I find the files in the SMTP service BADMAIL folder?
How can I find the files in the SMTP service PICKUP folder?
How can I find the files in the SMTP service QUEUE folder?
How to change the SMTP banner on Windows 2000
I am using the IIS Smtp service, how can I get a listing of undelivered messages?

User Accounts

How to Change the Display Names of Active Directory Users with Active Directory Services Interface Script
This article describes how to change the display names of Active Directory users with Active Directory Services Interface (ADSI) script.

Virtual Directories

How can I create a virtual directory and create an ASP application root at the same time?
How can I delete a virtual directory?
How can I view all virtual directory paths for a web site.

Web Sites

How can I create a web site with multiple host headers?
How can I delete a web site using ADSI?
How can I determine the number of sites I have such as Web and FTP on my server?
How can I display the Custom Errors defined for my Site?
How can I find a web site by Host Header name?
How can I get a listing of which sites are started or stopped?
How can I get a simple listing of the web sites and their home directories?
How can I get a simple listing of the web sites on my Web Server?
How can I retrieve/display the IIS Application name from a script?
How can I set my site so it can not be deleted in the MMC?
How can I set the application protection for a web site?
How can I view all the web site root directory paths?
How do I add a new default document to a Web Site?
How do I change the REALM what is displayed when in a Logon Dialog?
How do I create a web site, and an FTP site, and a EMAIL, and configure Front Page Server Extensions?
How do I enable document footers using a script?
How do I enumerate the physical and virtual folders on a particular IIS web site?
How do I find the next available Instance ID for a web site in the IIS Metabase?
How do I make sure that all web sites are running?
How do I start and stop one web site?
How do I unload an IIS Application?
HowTo: Create a virtual directory from an ASP page.
I manage more than 2000 sites with IIS, how can I tell which sites are running out of process?
This DLL enables you to install a website and a filter in IIS4 from InstallShield. The DLL uses ADSI and includes the C++ source


Microsoft Script Repository: Internet Information Server 5.x

Applications and Application Pools
Sample scripts for creating, deleting, and modifying application and application pools for Internet Information Server 5.0 and 5.1.

Basic Administration
Sample scripts for basic administration (such as backing up and restoring the metabase) of Internet Information Server 5.0 and 5.1.

Compression
Sample scripts for managing file compression on Internet Information Server 5.0 and 5.1.

FTP Sites
Sample scripts for managing FTP sites on Internet Information Server 5.0 and 5.1.

Web Sites
Sample scripts for managing Web sites on Internet Information Server 5.0 and 5.1.

Microsoft Script Repository: Internet Information Server 6.0

Applications and Application Pools
Sample scripts for creating, deleting, and modifying application and application pools for Internet Information Server 6.0.

Authentication
Sample scripts for managing authentication properties on Internet Information Server 6.0.

Basic Administration
Sample scripts for basic administration (such as backing up and restoring the metabase) of Internet Information Server 6.0.

BITS Server
Sample scripts for managing the BITS Server that ships with Internet Information Server 6.0.

Certificates
Sample scripts for managing certificate properties on Internet Information Server 6.0.

Compression
Sample scripts for managing file compression on Internet Information Server 6.0.

Filters
Sample scripts for managing filter properties on Internet Information Server 6.0.

FTP Sites
Sample scripts for managing FTP sites on Internet Information Server 6.0.

IMAP Server
Sample scripts for managing the IMAP mail server included with Internet Information Server 6.0.

Logging
Sample scripts for logs and logging options on Internet Information Server 6.0.

NNTP Server
Sample scripts for managing the NNTP news server included with Internet Information Server 6.0.

POP3 Server
Sample scripts for managing the POP3 mail server included with Internet Information Server 6.0.

SMTP Server
Sample scripts for managing the SMTP mail server included with Internet Information Server 6.0.

Web Sites
Sample scripts for managing Web sites on Internet Information Server 6.0.


IIS - Scripts - WMI - Enumerate all virtual directories on the local server

The following script will allow you to enumerate the names of the Virtual Directories on the current machine.

Save the following script to a .VBS file extension and execute using the following from a CMD.exe prompt.

cscript MyScript.vbs

Dim IISObj, strQuery, Item

Set IISObj = GetObject("winmgmts://./root/MicrosoftIISv2")
strQuery = "SELECT * FROM IIsWebVirtualDir" 
For Each Item In IISObj.ExecQuery(strQuery)
  WScript.echo Item.Name
Next

Example Output

W3SVC/1/ROOT
W3SVC/1/ROOT/_vti_bin
W3SVC/1/ROOT/Backup
W3SVC/1/ROOT/CertControl
W3SVC/1/ROOT/CertEnroll
W3SVC/1/ROOT/CertSrv
W3SVC/1/ROOT/ClientHelp
W3SVC/1/ROOT/ConnectComputer
W3SVC/1/ROOT/Exadmin
W3SVC/1/ROOT/Exchange
W3SVC/1/ROOT/exchange-oma
W3SVC/1/ROOT/ExchWeb
W3SVC/1/ROOT/ExchWeb/bin
W3SVC/1/ROOT/ExchWeb/bin/auth
W3SVC/1/ROOT/ExchWeb/bin/spell
W3SVC/1/ROOT/IssueVisionDeployWebCS
W3SVC/1/ROOT/IssueVisionWebCS
W3SVC/1/ROOT/Microsoft-Server-ActiveSync

IIS - Scripts - WMI - Enumerate Application Pools on Local Machine

The following script will allow you to enumerate the Names of the Application Pools on the current machine.

Save the following script to a .VBS file extension and execute using the following from a CMD.exe prompt.

cscript MyScript.vbs

Dim locatorObj, ProviderObj, Pools, strQuery

Set locatorObj = CreateObject("WbemScripting.SWbemLocator")
Set ProviderObj = locatorObj.ConnectServer(".", "root/MicrosoftIISv2")

strQuery = "Select * from IIsApplicationPool"
For Each Item In ProviderObj.ExecQuery(strQuery)
    WScript.Echo Replace(Item.Name, "W3SVC/AppPools/", "")
Next


Example Output

DefaultAppPool
ExchangeApplicationPool
ExchangeMobileBrowseApplicationPool
MSSharePointAppPool
MyWineCellar
StsAdminAppPool
WMS App Pool
Blog.crowe.co.nz