How to use PowerShell to create websites and application pools in IIS. A client of the company I work for wanted to quickly add 60 sub-domains to his website. But, the sub-domains had to be created as self contained IIS websites, and running in their own application pools. Luckily, the client wanted 60 consecutive sub-domain names, e.g. "sub01.example.com", "sub02.example.com", ..., ... up till "sub60.example.com". This made our task a bit easier, because we could easily script this in PowerShell
Create websites and application pools with PowerShell
To create the websites and application pools, we use PowerShell. If you follow the PowerShell example script below, keep in mind: a leading zero (0) for numbers lower than 10, an integer for your loop count and a numeric string as the website's identifier in IIS.
The quick 'n dirty PowerShell script to add the websites and application pools to IIS, we came up with is:
## subdomains need to run under the same idenity as the
## main (parent) website
$user = &appcmd.exe list apppool example.com /text:processmodel.username
$password = &appcmd.exe list apppool example.com /text:processmodel.password
$iis_id = 99999999
for ([int]$i = 1; $i -le 60; $i++)
{
[string]$id = $i
if ($i -lt 10) {
$id = "0$id"
}
$name = "sub$id.example.com"
$path = "D:\www\example.com\sub$id\www"
appcmd.exe add apppool /name:"$name" `
/autoStart:true
appcmd.exe set apppool /apppool.name:"$name" `
/managedRuntimeVersion:v4.0
appcmd.exe set apppool /apppool.name:"$name" `
/processmodel.identityType:SpecificUser
appcmd.exe set apppool /apppool.name:"$name" `
/processmodel.username:"$name"
appcmd.exe set apppool /apppool.name:"$name" `
/processmodel.password:"$password"
appcmd.exe add site /name:"$name" /id:$iis_id `
/physicalPath:"$path" /limits.maxconnections:1000 `
/serverAutostart:true
appcmd.exe set site /site.name:"$name" `
/+"bindings.[protocol='http',bindingInformation='*:80:$name']" `
appcmd.exe set app "$name/" /applicationPool:"$name"
## Need to remove the sites? Uncomment the following lines
## to remove websites and application pools:
##
# appcmd.exe delete apppool "$name"
# appcmd.exe delete site "$name"
# Write-Host "$name" deleted
## don't forget to comment the other lines of course :-)
$iis_id--
}
IIS website identifiers
Notice the $iis_id
in the above PowerShell script!
Since we're manually creating IIS website entries, IIS wants to automatically define a unique identifier for the website. If you go along with this, it might mess up your internal documentation and maintenance systems. We chose to set the identifier our self, with a very high number, to prevent conflicts with existing IIS website identifiers. Our identifier decreases with one (1) every run in the loop.
I hope this helps someone who has to do the same with PowerShell. Have a look at my other PowerShell posts for maintaining Windows Server and IIS.