Powershell scripting creation of a "sub" website

Viewed 1868

I have two folders:

c:\inetpub\site1
c:\inetpub\site1Sub

I want "site1" to be the "parent" website and "site1Sub" to be a "sub" website. Both sites should run under the same application pool, which is a custom pool created solely for these sites, call it "site1." In IIS Manager (7.5), I simply create the application pool, then the parent site, then right-click on the parent site and "Add Application," pointing it at the physical path "c:\inetpub\site1Sub." This all works fine.

When I try to script this in Powershell, however, things get difficult. I can create "site1" and the application pool with no problems. It's the sub-site that's being a pain. I've tried two approaches:

Approach 1: Use New-Item and set the app pool after.

$subSite = New-Item "IIS:\Sites\site1\site1Sub" -physicalPath "C:\inetpub\site1Sub" -type "Application"
$subSite | Set-ItemProperty -Name "applicationPool" -Value "site1"

With this approach, I receive an error after the Set-ItemProperty command:

Set-ItemProperty : Cannot find path 'C:\site1Sub' because it does not exist.
At line:1 char:127
+ $subSite | Set-ItemProperty -Name "applicationPool" -Value "site1"  ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\site1Sub:String) [Set-ItemProperty], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.SetItemPropertyCommand

Approach 2: Create a virtual directory and use ConvertTo-WebApplication (as in this answer).

New-WebVirtualDirectory -Site "site1" -Name "site1Sub" -PhysicalPath "c:\inetpub\site1Sub"
ConvertTo-WebApplication -ApplicationPool "site1" "IIS:\Sites\site1\site1Sub"

This runs fine, and further, it looks fine in IIS Manager, but when I attempt to navigate to the site I receive an error stating that the web.config failed to parse:

It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level. This error can be caused by a virtual directory not being configured as an application in IIS.

I'm totally stumped. How can I script this scenario in Powershell?

3 Answers
Related