Wednesday, August 6, 2014

IIS Websites Maintenance PowerShell script

File Name : IISMaintenance.ps1
This is the main script which need to edit to add the app pools and web site names to do a complete reboot of IIS apppools and websites in a proper order.

$appPoolNames = @(
    "DefaultAppPool";
    "www.wfactory.ca";
)

$webSiteNames = @(
    "Tsc";
    "TscM";
)

#Get-Location -This is automatic variable
#$scriptPath = $PSScriptRoot

$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition

CD $scriptPath

#Stop AppPools
foreach($appPool in $appPoolNames)
{
    Write-Host "Attempting to stop apppool :" $appPool
    ./AppPoolStartStop.ps1 -appPoolName $appPool -stop:$true
    Write-Host "Stopped apppool :" $appPool -foregroundcolor "green"
}

#Stop Websites
foreach($website in $webSiteNames)
{
    Write-Host "Attempting to stop website :" $website
    ./WebSiteStartStop.ps1 -websiteName $website -stop:$true
    Write-Host "Stopped website :" $website -foregroundcolor "green"
}

Start-Sleep -s 10

#Restart IIS
iisreset

#Start AppPools
foreach($appPool in $appPoolNames)
{
    Write-Host "Attempting to start apppool :" $appPool
    ./AppPoolStartStop.ps1 -appPoolName $appPool -stop:$false
    Write-Host "Started apppool :" $appPool -foregroundcolor "green"
}

#Start Websites
foreach($website in $webSiteNames)
{
    Write-Host "Attempting to start website :" $website
    ./WebSiteStartStop.ps1 -websiteName $website -stop:$false
    Write-Host "Started website :" $website -foregroundcolor "green"
}

Start-Sleep -s 10

File Name : AppPoolStartStop.ps1
The script accepts app pool name and a switch (Boolean) as parameters to start or stop a App Pool in IIS

param(
[string]$appPoolName,
[switch]$stop
)

$appPool = get-wmiobject -namespace "root\MicrosoftIISv2" `
           -class "IIsApplicationPool" `
           | where-object {$_.Name -eq "W3SVC/AppPools/$appPoolName"}

if($appPool)
{
   if($stop)
   {
      $appPool.Stop()
   }
   else
   {
      $appPool.Start()
   }
}
File Name : WebsiteStartStop.ps1
The script accepts website name and a switch (Boolean) as parameters to start or stop a Web site in IIS

param(
[string]$websiteName,
[switch]$stop
)

Import-Module WebAdministration

#[string]::IsNullOrEmpty(...)

if (!$websiteName)
{
    exit
}

if ($stop)
{
    Stop-WebSite $websiteName
}
else
{
    Start-WebSite $websiteName
}