Skip to content

Instantly share code, notes, and snippets.

@keyan1603
Last active September 5, 2024 19:56
Show Gist options
  • Select an option

  • Save keyan1603/0d627da29703a8fc41674743cda0c33a to your computer and use it in GitHub Desktop.

Select an option

Save keyan1603/0d627da29703a8fc41674743cda0c33a to your computer and use it in GitHub Desktop.
Schedule App Pool recycle on specific week days docker
# Variables
$taskName = "UpdateAppPoolRecycleTimes"
$taskDescription = "Update IIS App Pool recycling times based on day of the week."
$scriptPath = "C:\Scripts\UpdateRecycleTimes.ps1" # Full path to your PowerShell script
$user = "NT AUTHORITY\SYSTEM" # User account under which the task will run
$taskRunTime = "01:00" # Time to run the task daily
# Create a daily trigger for the task at a specified time
$trigger = New-ScheduledTaskTrigger -Daily -At $taskRunTime
# Create the action to run the PowerShell script
$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-ExecutionPolicy Bypass -File `"$scriptPath`""
# Register the scheduled task
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName $taskName -Description $taskDescription -User $user -Force
# Use the appropriate base image
FROM mcr.microsoft.com/windows/servercore:ltsc2019
# Copy the PowerShell script to the container
COPY set-recycle-schedule.ps1 /set-recycle-schedule.ps1
COPY CreateScheduledTask.ps1 /Scripts/CreateScheduledTask.ps1
# Run the PowerShell script to set the recycle schedule
RUN powershell -ExecutionPolicy Bypass -File /set-recycle-schedule.ps1
# Execute the script to create the scheduled task during container build
RUN powershell -ExecutionPolicy Bypass -File /Scripts/CreateScheduledTask.ps1
# Define the app pool name
$appPoolName = "DefaultAppPool"
# Get the current day of the week
$dayOfWeek = (Get-Date).DayOfWeek
# Define recycling times based on specific days
switch ($dayOfWeek) {
'Monday' {
$recycleTimes = @("02:00:00", "14:00:00")
}
'Wednesday' {
$recycleTimes = @("03:00:00", "15:00:00")
}
'Friday' {
$recycleTimes = @("04:00:00", "16:00:00")
}
default {
$recycleTimes = @("01:00:00", "13:00:00") # Default times for other days
}
}
# Clear existing recycle schedule
Remove-WebConfigurationProperty -pspath "MACHINE/WEBROOT/APPHOST" `
-filter "system.applicationHost/applicationPools/add[@name='$appPoolName']/recycling/periodicRestart/schedule" `
-name "."
# Add the new recycle times
foreach ($time in $recycleTimes) {
Add-WebConfigurationProperty -pspath "MACHINE/WEBROOT/APPHOST" `
-filter "system.applicationHost/applicationPools/add[@name='$appPoolName']/recycling/periodicRestart/schedule" `
-name "." -value @{ value = $time }
}
Write-Host "Recycle times added for $appPoolName for $dayOfWeek."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment