Friday, February 27, 2015

Changing Application Pool's recycle time


# Load Web Administration module
Import-Module WebAdministration

# Process idle timeout - Amount of time (in minutes) a worker process will remain idle before it shuts down
$idleTimeOut = "20"
# RegularTimeIntervalMinutes - Period of time (in minutes) after which the application pool will recycle.
$PeriodicRestart = "0"

function Set-ApplicationPoolRecycleTimes {
 
    param (
        [string]$ApplicationPoolName,
        [string[]]$RestartTimes
    )
     
      
    Write-Output "Updating recycle times for $ApplicationPoolName"
     
    # Delete all existing recycle times
    Clear-ItemProperty IIS:\AppPools\$ApplicationPoolName -Name Recycling.periodicRestart.schedule
     
    foreach ($restartTime in $RestartTimes) {
 
        Write-Output "Adding recycle at $restartTime"
        # Set the application pool to restart at the time we want
        New-ItemProperty -Path "IIS:\AppPools\$ApplicationPoolName" -Name Recycling.periodicRestart.schedule -Value @{value=$restartTime}
         
    } # End foreach restarttime
     
} # End function Set-ApplicationPoolRecycleTimes


function Set-RecyclingTimeoutSettings {
 
    param (
        [string]$ApplicationPoolName        
    )
     
    Write-Output "Setting worker process idle timeout to $idleTimeOut min. and periodic restart time to $PeriodicRestart for $ApplicationPoolName."
    $Pool = Get-Item IIS:\AppPools\"$ApplicationPoolName"
    #  A value of 0 means the process does not shut down after an idle timeout.
    $Pool.ProcessModel.IdleTimeout = [TimeSpan]::FromMinutes($idleTimeOut)
    # A value of 0 means the application pool does not recycle on a regular interval.
    $Pool.Recycling.PeriodicRestart.Time = [TimeSpan]::FromMinutes($PeriodicRestart)
    $Pool | Set-Item
      
} # End function RecyclingTimeoutSettings

# Get all app pools and change the iddle time-out and recycle time settings for each one of them
get-item IIS:\AppPools\* | %{
# Get a random specific time between 3-5 AM
$Offset = (Get-Random -Minimum 1 -Maximum 120) + 180
$restartat = (New-TimeSpan -Minutes $Offset).ToString()
$restartat = $restartat.Substring(0,5)
#$restartat = $null # comment out this line to disable specific time
# Set recycle time out settings
Set-RecyclingTimeoutSettings -ApplicationPoolName $_.name
# Set recycle time
Set-ApplicationPoolRecycleTimes -ApplicationPoolName $_.name -RestartTimes $restartat
}



No comments:

Post a Comment