Thursday, September 4, 2014

Powershell to Start the stopped Appools at a server

#The following powershell script will start the stopped apppools, the excluded a appools can be included in place of "Devtesting". Also this script will be in sleep mode in every 300 sec
===================================================================


Import-Module WebAdministration
$logPath = "D:\AppPool\logs\iis-recycle-" + (Get-Date).ToShortDateString() -replace "/","-"
$logPath += ".txt"
#Specify the time counter over here
$TimeCounter = 300
#Run in Infinite Loop
While ($true)
{
$Date = Get-Date
Write-Output $date | Out-File -FilePath $logPath -Append
$AppPools = Get-WmiObject -Class IIsApplicationPool -Namespace "root/MicrosoftIISv2" | Select-Object -property @{N="Name";E={$name = $_.Name; $name.Split("/")[2] }}
$ApppoolsEXclude = $AppPools | where-object {$_.Name -ne "Devtesting"}
foreach($Pool in $AppPoolsExclude)
{
$PoolName = $pool.Name
        $State = Get-WebAppPoolState -Name $PoolName
        $StateValue = $State.Value
        if($StateValue -eq "Stopped")
        {
            Write-Output "Found $PoolName as $StateValue. Proceeding to start..." | Out-File -FilePath $logPath -Append
            Start-WebAppPool -Name $PoolName
            if(-not $?)
            {
                Write-Output "Encountered an error. Pls check manually." | Out-File -FilePath $logPath -Append
            }
            else
            {
                Write-Output "Started" | Out-File -FilePath $logPath -Append
            }
        }
        else
        {
        }  
    }
     
   Write-Output "Proceeding to sleep for $TimeCounter seconds." | Out-File -FilePath $logPath -Append
   Sleep $TimeCounter
}