Creating IIS Applications with PowerShell

To help automate our functional testing, I need to use PowerShell to create the IIS application required to run Community Server on our build server. After searching around, I found some articles that showed how to programmatically create a virtual directory, but what I need is a virtual directory that is actually an *application* in the eyes of IIS.

Kind of surprisingly, it took digging into the IIS SDK and this article to find what I was looking for. So after reading that and some minor trial-and-error, here's what I came up with:

   1: # Get parameters passed to the script
   2: param($appName, $appPath)
   3:  
   4: $path = [ADSI]"IIS://localhost/W3SVC/1/ROOT"
   5: $app = $path.Create("IIsWebVirtualDir", $appName)
   6: $app.AppCreate2(1)
   7: $app.Put("AppFriendlyName", $appName)
   8: $app.Put("Path", $appPath)
   9: $app.Put("DefaultDoc", "Default.aspx")
  10: $app.SetInfo()
A few notes:
  • Line 4: This is the IIS path to the Default Web Site on localhost.
  • Line 5: This creates the virtual directory.
  • Line 6: This is what turns the virtual directory into an application.
  • Line 10: This saves the changes in IIS.
  • This script works in both IIS6 and IIS7.
  • This script assumes the app doesn't already exist in IIS. If it does, an error is thrown.

If you save this script in the root of your C: drive and name it CreateIISApp.ps1, this is how you'd run it:

create-iis-app

You could certainly enhance this script to check if the app already exists, or to pass in the server name and web site as parameters, but you get the general idea.

Tags: ,