Friday, 31 May 2013

Creating a Site in IIS Using PowerShell

So I have been doing a lot of work around build automation and continuous deployment lately and I thought I would do a quick post about setting up new website and application pool in IIS. I use this quite a bit in my daily work life, I use for creating development environments, test environments even remote production environments.

So firstly lets look at creating a new site and application pool:

 #Import the IIS Web Administration module
 Import-Module WebAdministration
 function AddSite($hostname, $siteRoot){
  #Check if the application pool already exists
  if (!(Test-Path "iis:\AppPools\$hostname")) {
   New-Item "iis:\AppPools\$hostname"

  $NewPool = Get-Item "iis:\AppPools\$hostname"
  #Set the application pool's account to NETWORK SERVICE
  $NewPool.ProcessModel.IdentityType = 2
  $NewPool | Set-Item

  #Set the application pool to .NET 4
  Set-ItemProperty "IIS:\AppPools\$hostname" managedRuntimeVersion v4.0

  #Check the site exists
  if (!(Test-Path "iis:\Sites\$hostname")) {
         #Create the site and bind it to the hostname, port and folder on disk
         New-Item "iis:\Sites\$hostname" -bindings @{protocol="http";bindingInformation=":80:$hostname"} -physicalPath "$siteRoot"

     #Set the site's application ppol<
     Set-ItemProperty "iis:\Sites\$hostname" -name applicationPool -value $hostname

And secondly lets look at removing the site and application pool:

function RemoveSite($hostname){
    if (Test-Path "iis:\Sites\$hostname") {
        #Remove the site
        Remove-Item "iis:\Sites\$hostname" -recurse

    if (Test-Path "iis:\AppPools\$hostname") {
        #Remove the application pool
        Remove-Item "iis:\AppPools\$hostname" -recurse

No comments:

Post a Comment