Install website in IIS using vbscript

Reference

In vbscript regular expression, you can use “SubMatches” collection to get the string you want to use. Before I found this, I had to get “Matches(0).Value” and replace unnecessary strings to empty string.

WScript.Echo FSO.FolderExists(“C:\temp\”)
Set Matches = regex.Execute(configLine)
WScript.Echo Matches(0).SubMatches(1)

The script parses website xml and does necessary actions. So, it uses regular expression heavily to parse the xml and get the right information. It has the following 5 operations

  • Get Site identifier from metabase xml file
  • Delete the site using identifier
  • Create all virtual directories if not exist
  • Install application pools and web site. This imports the xml.
  • Install SSL Certificate

This is the code

Dim fso, iisSiteId, webConfigPath
Set fso = CreateObject("Scripting.FileSystemObject")
webConfigPath = "..\IISSettings\Website.config"

iisSiteId = GetIisSiteIdentifier()      ' Read site identifier from xml file
If iisSiteId > 0 Then
    DeleteWebsite iisSiteId             ' Delete the existing web site
End If

CreateVirtualDirectories(webConfigPath) ' Create virtual directories

Call InstallAppPoolsWebSite             ' Install application pools and web site
InstallSSLCertificate iisSiteId         ' Install certificate    

Sub CreateVirtualDirectories(path)
    'On Error Resume Next

    Dim fl, strm, strLine, regex, Matches, fldPath
    Set fl = FSO.GetFile(path)
    Set strm = fl.OpenAsTextStream(1, -2)
    Set regex = New RegExp
    regex.Pattern = "(^\s*Path="")(.+)(""\s*$)"

    WScript.Echo "Creating virtual directories ..."
    Do Until strm.AtEndOfStream
        strLine = strm.ReadLine
        If regex.Test(strLine) = True Then
            Set Matches = regex.Execute(strLine)
            fldPath = Matches(0).SubMatches(1)
            If fso.FolderExists(fldPath) = False Then
                WScript.Echo fldPath
                CreateFolderRecursive(fldPath)
            End If
        End If
    Loop
End Sub

Function CreateFolderRecursive(path)
    CreateFolderRecursive = False
    If Not fso.FolderExists(path) Then
        If CreateFolderRecursive(fso.GetParentFolderName(path)) Then
            CreateFolderRecursive = True
            Call fso.CreateFolder(path)
        End If
    Else
        CreateFolderRecursive = True
    End If
End Function

Sub InstallAppPoolsWebSite()
    'If DefaultAppPoolPresent = False Then
    'If DefaultAppPoolPresent("DefaultAppPool") = False Then
    '    Import fso.GetFile("..\IISSettings\DefaultAppPool.config")
    'End If
    WScript.Echo "Installing Application Pools and Website"

    Dim flder, fls, fl
    Set flder = fso.GetFolder("..\IISSettings\")
    Set fls = flder.Files
    For Each fl in fls
        If InStr(fl.name, ".config") > 0 Then
            Import fso.GetFile(fl.Path)
        End If
    Next
End Sub

Sub InstallSSLCertificate (siteIdentifier)
    WScript.Echo "Installing SSL Certificate... to W3SVC/" & iisSiteId

    Dim iisCertObj
    Set iisCertObj = CreateObject("IIS.CertObj")
    iisCertObj.InstanceName = "W3SVC/" & siteIdentifier
    iisCertObj.Import "..\IISSettings\site_cert.pfx", "1234567", true, true
End Sub

''''''''''''''''''''''''''''''''''''''''''
' Find site identifier from settings xml '
''''''''''''''''''''''''''''''''''''''''''
Function GetIisSiteIdentifier()
    Dim SiteIdRegex, Matches
    Set SiteIdRegex = New RegExp
    SiteIdRegex.Pattern = "(""\/LM\/W3SVC\/)([0-9]+)("")"

    Dim fl, strm, strXml
    Set fl = fso.GetFile("..\IISSettings\Website.config")
    Set strm = fl.OpenAsTextStream(1, -2)
    Do
        strXml = strm.ReadLine
    Loop Until SiteIdRegex.Test(strXml) = True

    Set Matches = SiteIdRegex.Execute(strXml)
    GetIisSiteIdentifier = Matches(0).SubMatches(1)
End Function

''''''''''''''''''''''''''''''''
' Impoart App pool and website '
''''''''''''''''''''''''''''''''
Sub Import(objFile)
    Const IMPORT_EXPORT_MERGE     = 4
    Dim strPassword, IIsComputer, filePath, strXML
    Set IIsComputer = GetObject("winmgmts:{impersonationLevel=impersonate,authenticationLevel=pktPrivacy}!//localhost/root/MicrosoftIISv2:IIsComputer='LM'")
    strPassword = ""
    filePath = objFile.Path

    Set stream = objFile.OpenAsTextStream(1, -2)

    Do
       strXML = stream.ReadLine
    Loop Until InStr(strXML, "<> 0 Or InStr(strXML, "<> 0

    intFirst = InStr(1, strXML, """")
    strSourceMetabasePath = Mid(strXML, intFirst + 1, InStr(intFirst + 1, strXML, """") - intFirst - 1)
    strDestinationMetabasePath = strSourceMetabasePath
    WScript.Echo "Meta: " & strSourceMetabasePath
    intFlags = IMPORT_EXPORT_MERGE
    WScript.Echo "Importing: " & filePath & " " & strSourceMetabasePath
    IIsComputer.Import strPassword, filePath, strSourceMetabasePath, strDestinationMetabasePath, intFlags

    Start strSourceMetabasePath
End Sub

Sub Start(strWebServer)
   On Error Resume Next
   Set IIsWebServer = GetObject("winmgmts:{impersonationLevel=impersonate,authenticationLevel=pktPrivacy}!//localhost/root/MicrosoftIISv2:IIsWebServer='" & Mid(strWebServer, 5) & "'")
   IIsWebServer.Start
End Sub

''''''''''''''''''''''''''''''''''''''''''''''
' Check if DefaultApplicationPool is present '
''''''''''''''''''''''''''''''''''''''''''''''
'Function DefaultAppPoolPresent
Function DefaultAppPoolPresent(poolName)
    Dim appPools, appPool
    Set appPools = GetObject("IIS://localhost/W3SVC/AppPools")

    DefaultAppPoolPresent = False
    for each appPool in appPools
        if (appPool.Name = poolName) Then
            DefaultAppPoolPresent = True
        End If
    next
End Function

''''''''''''''''''''''''''''''''
' Delete the existing website  '
''''''''''''''''''''''''''''''''
Sub DeleteWebsite(identifier)
    On Error Resume Next
    Dim website
    Set website = Nothing
    Set website = GetObject("IIS://LocalHost/W3SVC/" & identifier) 

    If website Is Nothing Then
        WScript.Echo "Cannot find the existing website: " & identifier
    Else
        Set websiteParent = GetObject(website.Parent)
        WScript.Echo "Deleting: " & website.Class & " " & website.Name
        websiteParent.Delete website.Class, website.Name
    End If
End Sub
Install website in IIS using vbscript

9 thoughts on “Install website in IIS using vbscript

  1. Could you post an example for how the XML File must be written in order to setup an IIS WebPage?

    For me it seems to be a custom XML Format, or am I wrong?

    Thanks for your help
    Cheers
    – Gerhard

  2. simplelifeuk says:

    Hi, Gerhard.
    It is the xml file you can get when you select a website on IIS, right click, and select “All tasks > Save configuration to a file” The format looks like

    Visual Studio 2003 calles the script on PreBuild event.

  3. Of course all of this comes at a hefty price, but that
    would be involved if a fire collapse occurs fire extinguishers on one
    side of a building that was not on par with ordinances.
    They will not be able to hear a smoke alarm that fire extinguishers gives voice commands to
    wake your family up.

  4. I was recommended thjis blog by my cousin. I’m nott sure whether
    thyis post iis written byy hiim as nobody else now such detailed about my trouble.
    You are wonderful! Thanks!

  5. Having read this I believed it was rather informative.
    I appreciate you taking tthe time and effort tto put this article
    together. I once again find myself spending a lot of time both reading
    and posting comments. But so what, it was still worth it!

  6. Hello! I know this is kinda off topic nevertheless I’d figured I’d ask.
    Woulkd you be interested in exchanging links or maybe guest authoring a blog article or vice-versa?
    My site discusses a lot of the same subjects as yours
    and Ithink we could greatly benefit from each other. If you happen to be interested
    feel free to shoot me an e-mail. I look forward tto hearing from you!

    Superb blog by the way!

  7. I’m gone to inmform my little brother, that he should also pay a visit this web
    site on regular basis to obtain updated from most up-to-date gossip.

  8. In order to cook something like that, you only have to introduce the blender inside pot the location where the vegetables and fruit are boiling and mix the composition well
    a couple of times. There is a myriad of pre-prepared baby food about the market, but the key problem with this is that you’re never really
    sure what has gone into it, and there’s no shortage
    of studies to prove that the salt and sugar content articles are far higher than really appropriate for such a young child.
    They made their mark around the world within the 1950s for his or her revolutionary kitchen ideas,
    particularly with one of their food processors, dubbed the Kenwood
    Chef.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s